Search code examples
pythontkintercustomtkinterpython-vlc

How to fix the pause button?


I made a program that allows you to choose any audio to play using vlc module and tkinter.

The pause button didn't work. Even using global variable it didn't work.

#define "select file" function
def select_file():
    global filename
    filetypes = (
        ('MP3 files', '*.mp3'),)

    filename = fd.askopenfilename(
        title='Select audio', initialdir='/',
        filetypes=filetypes)

#define "play audio" function
def play():
    p = vlc.MediaPlayer(filename)
    p.play()
#define "pause audio" function
def pause():
    p = vlc.MediaPlayer(filename)
    p.stop()

#open button
open_button = customtkinter.CTkButton(master=frame_1, text="Select file", command=select_file)
open_button.pack(pady=10, padx=10)

#play button
play_button = customtkinter.CTkButton(master=frame_1, text="Play", command=play)
play_button.pack(pady=10, padx=10)

#pause button
pause_button = customtkinter.CTkButton(master=frame_1, text="Pause", command=pause)
pause_button.pack(pady=10, padx=10)

Solution

  • Inside pause(), you need to use the instance of vlc.MediaPlayer() created inside play() instead of creating a new one.

    I would suggest to create the instance once outside the functions:

    # create the player once
    player = vlc.MediaPlayer()
    
    #define "select file" function
    def select_file():
        global filename
        filetypes = (
            ('MP3 files', '*.mp3'),)
    
        filename = fd.askopenfilename(
            title='Select audio', initialdir='/',
            filetypes=filetypes)
    
        if filename:
            # set the song to play
            player.set_mrl(filename)
    
    #define "play audio" function
    def play():
        player.play()
    
    #define "pause audio" function
    def pause():
        player.pause()  # use .pause() instead of .stop()