pythonvlcpafy

Stream Music from YouTube with Python


I'm looking to create a script that will pull a YouTube video url from a database and play it in a program using Python.

I currently have pafy and vlc setup and it works, but not exactly how I need it to.

import time, pafy, vlc, youtube_dl

url = "https://www.youtube.com/watch?v=qcCH6JpcK5w"
video = pafy.new(url)
best = video.getbest()
playurl = best.url

Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new(playurl)
Media.get_mrl()
player.set_media(Media)
duration = player.get_length() / 1000
player.play()
time.sleep(duration)

This will load the url and open up vlc player, which plays the video.

I would like to just be able to play the music without the vlc player. I was reading up on ffmpeg, but I'm not sure how/if it would work.

Any direction/insight would be helpful. Thank you.


Solution

  • You can pass command line options to the vlc Instance.
    So any option (I guess within reason) you can specify on the command line, can be passed into the Instance within python.

    As there is a --no-video command line option, you can add that.
    i.e.

    Instance = vlc.Instance('--no-video ')
    

    You can pass as many options as you like, just make sure they are space separated.