0

我正在尝试使用 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 然后停止时,视频仍在播放。

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

4

1 回答 1

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']
于 2021-10-09T22:39:13.660 回答