python-vlc 无法播放和响应 youtube 视频 link?

python-vlc doesn't plays and response with the youtube video link?

我一直在尝试使用 pafypython-vlc 从 python 播放 YouTube link。代码编译并完成,但 link 没有通过 vlc 播放,即使我在底部调用了 play()

我已经尝试卸载现有的 python-vlc 并重新安装它,但问题仍然存在,我对上面的代码 运行 使用 sublime 文本编辑器,所以我用 python IDLE 尝试了这个但一切都是:

一样

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()

我预计视频会作为输出播放,但实际上它在没有任何响应和错误的情况下结束了

使用 作为起点,我能够添加一些调试以查看发生了什么。 看起来您的 python 代码在 vlc 运行 之前退出。所以我想出了这个解决方案,我用几个不同的 URL 测试了它,它似乎有效。

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()

或者您可以使用事件查看 VLC Python EventManager callback type?