This article covers the Pygame Mixer for audio and music.
No matter how great a game’s visuals and gameplay are, it’s not complete without a great soundtrack and music. Sound and Music are an important part of Video game immersion, and the experience is just lacking and empty without them.
The Python Pygame Mixer Library brings in support Audio and Sound playback. The great thing about it is that it’s not just restricted to making games. You can use the Mixer library all on it’s own as a stand alone library to play sound and music in your average Python program.
The sound effects used in this article have been acquired from the site, Freesound. You can find thousands of different sound effects for your program from this site, free of of charge or copyright issues. If you want to know more about the license under which these are available, follow this link.
Using the Mixer
First thing to know is that there is a difference between Music and Sound in the Pygame Mixer. Make sure to not confuse the two. Sound is mostly related to small side effects such as crash noises or beeps, generally anything just a few seconds long.
Music, on the other hand refers to longer tracks of audio, like background music or songs which can be up-to an hour long. It’s important to know this difference since there are separate libraries for Music and Sound.
Next, you should know about the types of files we’ll be using. The pygame mixer has the best support for
wav files. It does support
mp3, but not very reliably, so it’s best to stick to
wav files for maximum compatibility.
Pygame Mixer – Music
We’ll cover music first as it’s the larger and more complex library.
First thing to do is load up the appropriate music file into the
music.load() function. Remember to keep both in the same directory else you’ll have to mention the full file path.
Now comes the
music.play() function, which is used to play the audio clip that has been loaded up. This function can be called in a variety of manners to change how it plays the audio clip.
pygame.mixer.music.play(0) pygame.mixer.music.play(5) pygame.mixer.music.play(-1)
music.play() with no parameters or
0 passed into it will only play the audio clip once. Passing
-1 as the parameter will play the audio clip indefinitely.
Passing any other positive integer besides 0 will result in the song being repeated that many times. For instance, passing
5 will repeat the song 5 times. So the song played once, and repeated 5 times, playing a total of 6 times.
The Music library only allows one music file to be loaded and played at any given time. However, you are allowed to “queue” audio clips using the
music.queue() function. Audio that has been queued will play right after the current music playing ends.
All things must come to end, and so too must music. The
music.stop() function is used like the “stop” button on an audio player. Do not confuse this with pause. The stop function will end your current music playback and if you call the
play() function again, it will start from the beginning.
Music.pause() and Music.unpause()
Now obviously, you don’t always want to be using
music.stop(). Sometimes you just want to pause so that you can pick up things later as you left them. Calling the
music.pause() function will pause the music as it is.
Calling the unpause() function will resume the music.
Another interesting function in the
pygame.mixer.music() library is the
set_endevent() function. This function takes a number as a parameter and triggers the corresponding event once the music has stopped playing.
SONG_END_EVENT = pygame.USEREVENT + 1 while True: for event in pygame.event.get(): if event.type == SONG_END: # Code to be executed
pygame.USEREVENT and adding 1 ensures that the value of our user defined event is unique.
Other less common functions in the
pygame.mixer.music() library are listed below.
pygame.mixer.music.rewind()– Rewinds the currently playing music to the start.
pygame.mixer.music.set_volume() – Takes values in between 0.0 and 1.0. When a new music piece is loaded, these settings reset.
pygame.mixer.music.get_busy() – Checks to see if music is currently playing or not. Returns False if not playing and True if it is.
Pygame Mixer – Sound
Using simple sound files in Pygame is much simpler than playing music.
There are two steps involved in playing a sound. First you must create a sound object, as shown below.
sound_effect = pygame.mixer.Sound('crash.wav')
Next we call it with a simple
play() method. An alternate option is to use the
Sound.play() function, but that’s longer.
Unlike music, we can have multiple sound objects at any one point, though don’t try to play more than one at a time.
To top it all off, we’ll show you a short demonstration of all the concepts discussed above. We’ve created a mini program using the GUI software Tkinter with buttons to control the music and sound. You won’t normally be using Tkinter with Pygame, but this is a good demonstration anyway. Especially if you’re looking to use only the Pygame mixer.
We’ve shown this demonstration in a video, and we’ve also included the source code here for you to practice with.
import pygame from tkinter import * def play(): pygame.mixer.music.load('background.wav') pygame.mixer.music.play() def pause(): pygame.mixer.music.pause() def unpause(): pygame.mixer.music.unpause() def sound(): pygame.mixer.Sound.play(sound_effect) pygame.init() sound_effect = pygame.mixer.Sound('crash.wav') root = Tk() root.geometry('180x200') myframe = Frame(root) myframe.pack() mylabel = Label(myframe, text = "Pygame Mixer") mylabel.pack() button1 = Button(myframe, text = "Play", command = play, width = 15) button1.pack(pady = 5) button2 = Button(myframe, text = "Sound", command = sound, width = 15) button2.pack(pady = 5) button3 = Button(myframe, text = "Unpause", command = unpause, width = 15) button3.pack(pady = 5) button4 = Button(myframe, text = "Pause", command = pause, width = 15) button4.pack(pady = 5) root.mainloop()
Other Audio Libraries
There are many different python libraries that can be used for audio playback, and the Pygame Mixer is just one of them. We’ll briefly describe one or two other Audio libraries that you can use instead.
- playsound: Created with the purpose of being a simple one line function library. However, it has no functionality beyond audio playback of
- simpleaudio: Another library used for cross platform and dependency free audio playback .
If you want to learn more about Pygame as a game development library, I recommend you our tutorial series on Pygame.
This marks the end of the Python Pygame Mixer article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article can be asked in the comments section below.