停止 python-vlc: player.stop() 不起作用

Stopping python-vlc: player.stop() doesn't work

我正在尝试使用 pafy 和 vlc 播放 YouTube 视频:

def run(command, args, voice_instance):
    if command == "pune":
        search_query = " ".join(args)
        result = YoutubeSearch(search_query, max_results=10).to_dict()[0]

        video_title = result["title"]
        url_suffix = result["url_suffix"]

        url = f"https://www.youtube.com/{url_suffix}"
        video = pafy.new(url)
        best = video.getbest()
        playurl = best.url
        Instance = vlc.Instance("--no-video")
        player = Instance.media_player_new()
        Media = Instance.media_new(playurl)
        Media.get_mrl()
        player.set_media(Media)
        voice_instance.say(f'Pun {video_title}')
        player.play()
    
    if "oprește" in command:
        print('1')
        player.stop()
        print('2')

它播放视频,但当我说 opreste 它打印 1 然后停止,视频仍在播放。

关于如何解决这个问题的任何想法?

开玩笑,但如果你能做的只是提供一个函数,也许你可以将你的播放器存储为全局变量?

def run(command, args, voice_instance):

    if globals().get('player'):
        instance = globals()['instance']
        player = globals()['player']
    else:
        instance = globals()['instance'] = vlc.Instance("--no-video")
        player = globals()['player'] = instance.media_player_new()    

    if command == "pune":
        search_query = " ".join(args)
        result = YoutubeSearch(search_query, max_results=10).to_dict()[0]

        video_title = result["title"]
        url_suffix = result["url_suffix"]

        url = f"https://www.youtube.com/{url_suffix}"
        video = pafy.new(url)
        best = video.getbest()
        playurl = best.url

        media = instance.media_new(playurl)
        media.get_mrl()
        player.set_media(media)

        voice_instance.say(f'Pun {video_title}')
        player.play()
    
    if "oprește" in command:
        print('1')
        player.stop()
        print('2')
        # and possibly garbage collect the player
        # del globals()['player']
        # del globals()['instance']