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.
99pygame.mixer.init()
100
101# Initialize pygame
102pygame.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/
132pygame.mixer.music.load("sound/Sky_dodge_theme.ogg")
133pygame.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.
194pygame.mixer.music.stop()
195pygame.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:
helenyip2 on March 21, 2020
Sky_dodge_theme.ogg
file is not in the folder via the link provided.