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
Sample Code: Click here to download the source code for the PyGame sample project used in this tutorial.
As with most things in
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
.mixer.init(), check out the following resources from the
For more information about the types of audio files that
pygame supports for music playback, check out the following resources:
Comments & Discussion
Become a Member to join the conversation.