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

2.4k Views Asked by At

I am trying to play a youtube video using pafy and vlc:

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

It plays the video, but when i say opreste it prints 1 then stops, and the video is still playing.

Any ideas on how could i fix this ?

1

There are 1 best solutions below

0
psarka On BEST ANSWER

Shooting off the hip, but if all you can do is provide a single function, maybe you can store your player as a global variable?

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']