Python Forum
integrate pygame mixer into a class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
integrate pygame mixer into a class
#1
I am trying to use pygame mixer to play sounds in my little game, but I am having trouble. Can anyone help?

Here I am just trying to select music in a listbox and play the track.

What is the best way to integrate mixer into my little class Music()? Pass mixer as a parameter?

The code below works, but I have a feeling this could be done better.

import tkinter as tk
from tkinter.messagebox import showinfo
from tkinter import ttk
import pygame.mixer as mixer

class Music():
    slide_sound_bite =  "/home/peterr/PVE/pyglet/sound_bites/slide_sound1.mp3"
    clap_sound_bite =  "/home/peterr/PVE/pyglet/sound_bites/clap_cheer.mp3"
    bgmusic =  "/home/peterr/PVE/pyglet/sound_bites/bolero.mp3"

    def __init__(self):
        self.mplayer = mixer
        self.mplayer.init()
        self.root = tk.Tk()
        self.root.geometry('400x180')
        self.root.title('Listbox')
        # create a variabe object
        #languages = ('Java', 'C', 'C++', 'C#', 'Python', 'Go', 'JavaScript', 'PHP', 'Swift')
        self.tracks = [self.slide_sound_bite, self.clap_sound_bite, self.bgmusic]
        self.list_variable = tk.Variable(value=self.tracks)
        # label
        self.info = ttk.Label(self.root, text='Select your favorite music:')
        self.info.pack(padx=10, pady=0, side=tk.TOP, fill=tk.X)
        #listbox = tk.Listbox(root, listvariable=list_variable, height=6, selectmode=tk.MULTIPLE)
        self.listbox = tk.Listbox(self.root, listvariable=self.list_variable, height=6, selectmode=tk.BROWSE)
        self.listbox.pack(padx=10, pady=10, expand=True, fill=tk.BOTH, side=tk.LEFT)             
        # link a scrollbar to a list
        self.v_scrollbar = ttk.Scrollbar(self.root, orient=tk.VERTICAL, command=self.listbox.yview)
        self.listbox['yscrollcommand'] = self.v_scrollbar.set
        self.v_scrollbar.pack(pady=10, side=tk.RIGHT, fill=tk.Y)
        # this passes an event to handle_item_select()
        self.listbox.bind('<<ListboxSelect>>', lambda x: self.handle_item_select(x))
        self.root.mainloop()

    def handle_item_select(self, event):
            selected_indices = self.listbox.curselection()
            print(f'selected_indices are {selected_indices}')
            selected_track = ",".join([self.listbox.get(i) for i in selected_indices])            
            #showinfo(title='Information', message=f'You selected: {selected_track}')
            self.mplayer.music.load(selected_track)
            self.mplayer.music.play()
            #p = Music()
I am using the module pyglet at present, but, when I close my game, I see a gstreamer CRTICAL error (after the game is closed). Can't find how to deal with that!
Reply
#2
You do not need to pass pygame.mixer into the class. It is a module,so importing it and initializing it once is normal.
Here a test that work for me,improvement so it cleanly stop the music and shut down the mixer before destroying the Tkinter window.
from pathlib import Path
import tkinter as tk
from tkinter import ttk
import pygame

class MusicPlayer:
    def __init__(self, root):
        self.root = root
        pygame.mixer.init()
        sound_dir = Path("F:/1_youtube/audio_mp3")
        self.tracks = [
            sound_dir / "Dreamstate Feat. Elize Ryd - Evolution.mp3",
            sound_dir / "Kygo, Ava Max - Whatever (Official Video).mp3",
        ]
        self.track_names = [track.name for track in self.tracks]
        self.list_variable = tk.StringVar(value=self.track_names)
        ttk.Label(root, text="Select your favorite music:").pack(padx=10, fill=tk.X)
        frame = ttk.Frame(root)
        frame.pack(padx=10, pady=10, expand=True, fill=tk.BOTH)
        self.listbox = tk.Listbox(
            frame,
            listvariable=self.list_variable,
            height=6,
            selectmode=tk.BROWSE,
        )
        self.listbox.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)
        scrollbar = ttk.Scrollbar(
            frame,
            orient=tk.VERTICAL,
            command=self.listbox.yview,
        )
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.listbox.configure(yscrollcommand=scrollbar.set)
        self.listbox.bind("<<ListboxSelect>>", self.play_selected)
        root.protocol("WM_DELETE_WINDOW", self.close)

    def play_selected(self, event=None):
        selection = self.listbox.curselection()
        if not selection:
            return

        index = selection[0]
        selected_track = self.tracks[index]
        pygame.mixer.music.load(str(selected_track))
        pygame.mixer.music.play()

    def close(self):
        pygame.mixer.music.stop()
        pygame.mixer.music.unload()
        pygame.mixer.quit()
        self.root.destroy()

root = tk.Tk()
root.geometry("400x180")
root.title("Music player")
app = MusicPlayer(root)
root.mainloop()
Pedroski55 likes this post
Reply
#3
Thanks for your help!

I wish I could do this:

def close(self):
        pygame.mixer.music.stop()
        pygame.mixer.music.unload()
        pygame.mixer.quit()
        self.root.destroy()
with pyglet, but

Quote:Pyglet’s Player has no stop() method — to quit playback you must call player.pause() and then exit or close the window using pyglet.app.exit() or window.close().

But I never start pyglet.app.run(), because tkinter is doing the window managing, not pyglet. If I put pyglet.app.run() in my class, the class will not start!

I tried this:

def quit_tk(self):
        self.mplayer.pause()
        self.mplayer = None
        #pyglet.app.exit()
        self.root.destroy()
        print('Tkinter window closed ✅')
but I still get the gstreamer CRITICAL error!

I think pyglet wants to do everything, create the window, make the whole game using pyglet. So that's why I am trying pygame.mixer!
Reply
#4
Safari says "Combining Pyglet and Tkinter in the same application is theoretically possible, but highly discouraged..." Then it talks about how to do it, launching tkinter first, then having tkinter launch pyglet. Once both are running, using threading or multiprocessing to communicate between the two.

Copilot says "You can integrate Pyglet with Tkinter, but it requires careful management of their separate event loops, often using threading or callbacks to prevent the GUI from freezing."
Reply
#5
I testet and got pyglet to work(can post it if want to look at it),but pygame.mixer is better suited for this task.
To make it look better use eg CustomTkinter, here test added play,stop and volume control.
from pathlib import Path
import customtkinter as ctk
import pygame

ctk.set_appearance_mode("System")   # "System", "Dark", or "Light"
ctk.set_default_color_theme("blue") # "blue", "green", or "dark-blue"

class MusicPlayer(ctk.CTk):
    def __init__(self):
        super().__init__()
        self.title("Music Player")
        self.geometry("600x390")
        self.minsize(500, 350)
        pygame.mixer.init()
        pygame.mixer.music.set_volume(0.7)
        sound_dir = Path("F:/1_youtube/audio_mp3")
        self.tracks = [
            sound_dir / "Dreamstate Feat. Elize Ryd - Evolution.mp3",
            sound_dir / "Kygo, Ava Max - Whatever (Official Video).mp3",
        ]

        self.selected_track = ctk.StringVar(value="")
        self.create_widgets()
        # Cleanly close pygame before closing the window.
        self.protocol("WM_DELETE_WINDOW", self.close_app)

    def create_widgets(self):
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(1, weight=1)
        title = ctk.CTkLabel(
            self,
            text="Select your favorite music",
            font=ctk.CTkFont(size=22, weight="bold"),
        )
        title.grid(row=0, column=0, padx=20, pady=(20, 10))
        self.track_frame = ctk.CTkScrollableFrame(
            self,
            label_text="Available tracks",
        )
        self.track_frame.grid(
            row=1,
            column=0,
            padx=20,
            pady=10,
            sticky="nsew",
        )
        self.track_frame.grid_columnconfigure(0, weight=1)
        for row, track in enumerate(self.tracks):
            radio_button = ctk.CTkRadioButton(
                self.track_frame,
                text=track.name,
                variable=self.selected_track,
                value=str(track),
                command=self.play_selected,
            )
            radio_button.grid(
                row=row,
                column=0,
                padx=15,
                pady=10,
                sticky="w",
            )
        controls = ctk.CTkFrame(self, fg_color="transparent")
        controls.grid(row=2, column=0, padx=20, pady=10, sticky="ew")
        controls.grid_columnconfigure((0, 1), weight=1)
        play_button = ctk.CTkButton(
            controls,
            text="Play",
            command=self.play_selected,
        )
        play_button.grid(row=0, column=0, padx=(0, 5), sticky="ew")

        stop_button = ctk.CTkButton(
            controls,
            text="Stop",
            command=self.stop_music,
        )
        stop_button.grid(row=0, column=1, padx=(5, 0), sticky="ew")

        volume_label = ctk.CTkLabel(controls, text="Volume")
        volume_label.grid(row=1, column=0, padx=5, pady=(15, 0))
        self.volume_slider = ctk.CTkSlider(
            controls,
            from_=0.0,
            to=1.0,
            command=self.change_volume,
        )
        self.volume_slider.set(0.7)
        self.volume_slider.grid(
            row=1,
            column=1,
            padx=5,
            pady=(15, 0),
            sticky="ew",
        )
        self.status_label = ctk.CTkLabel(
            self,
            text="Select a track to begin",
            anchor="w",
        )
        self.status_label.grid(
            row=3,
            column=0,
            padx=20,
            pady=(0, 15),
            sticky="ew",
        )

    def play_selected(self):
        selected = self.selected_track.get()
        if not selected:
            self.status_label.configure(text="No track selected")
            return
        track = Path(selected)
        if not track.is_file():
            self.status_label.configure(
                text=f"File not found: {track.name}"
            )
            return

        try:
            pygame.mixer.music.load(str(track))
            pygame.mixer.music.play()

            self.status_label.configure(text=f"Playing: {track.name}")
        except pygame.error as error:
            self.status_label.configure(text=f"Could not play track: {error}")

    def stop_music(self):
        pygame.mixer.music.stop()
        self.status_label.configure(text="Playback stopped")

    def change_volume(self, volume):
        pygame.mixer.music.set_volume(float(volume))

    def close_app(self):
        pygame.mixer.music.stop()
        try:
            pygame.mixer.music.unload()
        except pygame.error:
            pass

        pygame.mixer.quit()
        self.destroy()

if __name__ == "__main__":
    app = MusicPlayer()
    app.mainloop() 
Reply
#6
Thanks for the tips.

@snippsat: I have a folder called snippsat, I always save your code in it, for future reference! Thank you!

As I said, my little game does just what I want. I use pyglet, no problem.

The problem only appears when I close the game, then I see the gstreamer CRITICAL error. In Linux at least, pygame uses gstreamer.

Maybe I could use the module signal and send a SIGINT to gstreamer when quitting the game??

I have these functions for controlling the music using pygame mixer:

# Play, Stop, Load and Pause & Resume functions
    def play_song(self):
        current_song.set(songs_list.get(ACTIVE))
        mixer.music.load(songs_list.get(ACTIVE))
        mixer.music.play()
        status.set("Song PLAYING")

    def stop_song(self):
        self.mixer.music.stop()
        self.song_status.set("Song STOPPED")

    def load(self):
        os.chdir(filedialog.askdirectory(title='Open a songs directory'))
        tracks = os.listdir()
        for track in tracks:
            self.playlist.insert(tk.END, track)

    def pause_song(self):
        self.mixer.music.pause()
        self.song_status.set("Song PAUSED")

    def resume_song(self):
        self.mixer.music.unpause()
        self.song_status.set("Song RESUMED")
I didn't have one for volume yet, thanks for that!!
Reply
#7
Hope you can see this image

Works fine, but the Play button is redundant. Not entirely redundant. If I want to play the selected radio button sound again, press Play. First time it plays without recourse to Play.

When I click the radio button, the sound starts immediately. (NOT a COMPLAINT, I want to link the sounds in a menu item to switch them on and off anyway.)

I was only trying to create a music player to see how to use pygame mixer.
Reply
#8
In case anyone is interested:

Using pygame mixer, if you want to play different short sound effects and a longer music track, without mutual interruption, you need more than 1 mixer, (or stream??).

Try like this:

slide_sound_bite =  "/home/peterr/PVE/pyglet/sound_bites/slide_sound1.mp3" # about 1/2 second
clap_sound_bite =  "/home/peterr/PVE/pyglet/sound_bites/clap_cheer.mp3" # about 1 minute
bgmusic =  "/home/peterr/PVE/pyglet/sound_bites/bolero.mp3"

mixer.init()    
slide = mixer.Sound(slide_sound_bite)
clap = mixer.Sound(clap_sound_bite)
To play the a short sound bite:

clap.play()
or

slide.play()
The background music is longer, 16 minutes. To start with, I set the background music playing:

mixer.music.load(self.bgmusic)
mixer.music.play()
Then you can use:

mixer.music.pause()
or

mixer.music.unpause()
to start and stop the background music.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to Integrate External Content into a Python Web App + Related Resource finallen321 1 737 Dec-27-2025, 06:21 PM
Last Post: noisefloor
  mute spotify by the mixer of volume garze23 0 1,393 Feb-27-2024, 05:42 PM
Last Post: garze23
  Integrate/import a gui code to my main.py penahuse 6 5,881 Feb-03-2021, 08:49 PM
Last Post: deanhystad
  Pygame mixer and tkinter music player Kumarkv 1 4,342 May-14-2020, 06:08 PM
Last Post: Larz60+
  Trypng to use pygame mixer Larz60+ 4 5,537 Mar-21-2018, 09:08 PM
Last Post: Larz60+
  Pygame*import pygame ImportError: No module named pygame CASPERHANISCH 1 11,311 Jun-05-2017, 09:50 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020