'SOLVED: Python interacting with VLC through Tkinter: I want to be able to change between videos

I am making a python tkinter utility that makes a youtube search, brings up the first 6 results, and than plays the chosen of those results through a vlc instance.

The problem I have, is that when I try to change the video, it just opens a second VLC instance, and two musics start playing at the same time.

So my question is: how do I use the same instance of vlc, to first play one piece of music, and then the next. Or if necesary, how do I destroy the instance of VLC to make the next one.

Here is the code I tried; the experiment that doesnt work is within the function "func" (not the one that is made into comments). The code is by the way not my actual project, but just an experiment.

import vlc  
import time
import pafy
from tkinter import *

url = "https://www.youtube.com/watch?v=yV25KhUH1BE"                                                                                   
win = Tk()
pause = 0

#def func():
#   global pause
#   pause = -(pause-1)
#   player.set_pause(pause)

def func():
    url = "https://www.youtube.com/watch?v=PrxLttEc8do"
    video = pafy.new(url)                                                                                                                       
    best = video.getbestaudio()                                                                                                                 
    playurl = best.url
    media=instance.media_new(playurl)
    media.get_mrl()
    player.set_media(media)

btn = Button(win,
                    text = "Change video",
                    command =  func)



video = pafy.new(url)                                                                                                                       
best = video.getbestaudio()                                                                                                                 
playurl = best.url 

instance = vlc.Instance()
player = instance.media_player_new()                                                                                                         
media=instance.media_new(playurl)
media.get_mrl()
player.set_media(media)
player.play()
btn.pack()



win.mainloop()


Solution 1:[1]

Your example code works fine, it doesn't play multiple songs.

I think that in your actual code you are calling player = instance.media_player_new() whenever you play a new song. Make sure this is piece of code is outside of the function and only ever called once.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gprime