Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.

Adding Music

In this lesson, you’ll add background music to your game. The sounds and music you will use in this lesson and the next are in the sound directory:

As with most things in pygame, using mixer starts with an initialization step:

 98 # Setup for music and sounds. Defaults are good.
 99 pygame.mixer.init()
100 
101 # Initialize pygame
102 pygame.init()

After the system is initialized, you can get your background music setup:

129 # Load and play background music
130 # Sound source: Chris Bailey - artist Tripnet
131 # License: https://creativecommons.org/licenses/by/3.0/
132 pygame.mixer.music.load("sound/Sky_dodge_theme.ogg")
133 pygame.mixer.music.play(loops=-1)

Finally, when the game is over, all sounds should stop. This is true whether the game ends due to a collision or the user exits manually. To do this, add the following lines at the end of the program after the loop:

193 # All done! Stop and quit the mixer.
194 pygame.mixer.music.stop()
195 pygame.mixer.quit()

For more information about the music module, mixer, and .mixer.init(), check out the following resources from the pygame documentation:

For more information about the types of audio files that pygame supports for music playback, check out the following resources:

Comments & Discussion

helenyip2 on March 21, 2020

Sky_dodge_theme.ogg file is not in the folder via the link provided.

helenyip2 on March 21, 2020

Nevermind! I found it when I downloaded the Code zip file under Suppporting Materials.

Pawe on March 29, 2020

Same here! Thank @helenyip2 for pointing the references to files.

Become a Member to join the conversation.