Reputation: 43
I have been trying to play the YouTube links from python using pafy
and python-vlc
. The code compiles and finishes but the link doesn't play through vlc
even though I have called play()
at bottom
I have tried uninstalling the existing python-vlc
and reinstalling it but the problem persists, I was using sublime text editor for running above code and so I tried this with python IDLE but everything was:
same
import vlc
import pafy
url = "https://www.youtube.com/watch?v=VwsmkB-YpJo"
video = pafy.new(url)
best = video.getbest()
playurl = best.url
ins = vlc.Instance()
player = ins.media_player_new()
Media = ins.media_new(playurl)
Media.get_mrl()
player.set_media(Media)
player.play()
I expected as an output the video will play but actually it finished up with no any response and errors
Upvotes: 0
Views: 3552
Reputation: 9430
Using open url error using vlc in terminal as a starting point I was able to add some debug to see what was going on. It looks like your python code exits before vlc is running. So I came up with this solution, I have tested it with several different URLs and it seems to work.
import vlc
import pafy
import urllib.request
url = "https://www.youtube.com/watch?v=9W3A34TTxFU&list=RD9W3A34TTxFU&start_radio=1"
video = pafy.new(url)
best = video.getbest()
playurl = best.url
ins = vlc.Instance()
player = ins.media_player_new()
code = urllib.request.urlopen(url).getcode()
if str(code).startswith('2') or str(code).startswith('3'):
print('Stream is working')
else:
print('Stream is dead')
Media = ins.media_new(playurl)
Media.get_mrl()
player.set_media(Media)
player.play()
good_states = ["State.Playing", "State.NothingSpecial", "State.Opening"]
while str(player.get_state()) in good_states:
print('Stream is working. Current state = {}'.format(player.get_state()))
print('Stream is not working. Current state = {}'.format(player.get_state()))
player.stop()
Or you can use events see VLC Python EventManager callback type?
Upvotes: 2