Game Development Reference
In-Depth Information
pygame.mixer
module is responsible for playing short sound effects during the game.
The
pygame.mixer.music
module is used for playing background music.
We will call the
pygame.mixer.Sound()
constructor function to create a
pygame.mixer.Sound
object (which we will simply call a
Sound
object). This object
has a
play()
method that when called will play the sound effect.
On line 39 we load the background music by calling pygame.mixer.music.load(). We
will start playing the background music immediately by calling
pygame.mixer.music.play()
. The first parameter tells Pygame how many times to
play the background music after the first time we play it. So passing
5
will cause Pygame
to play the background music 6 times over. If you pass
-1
for the first parameter, the
background music will repeat itself forever.
The second parameter to
pygame.mixer.music.play()
tells at what point in the
sound file to start playing. Passing
0.0
will play the background music starting from the
very beginning. If you passed
2.5
for the second parameter, this will cause the background
music to start playing two and half seconds after the start of the music.
Finally, we have a simple boolean variable named
musicPlaying
that will tell our
program if it should play the background music and sound effects or not. It is nice to give
the player the option to run the program without the sound playing.
Toggling the Sound On and Off
79. if event.key == ord('m'):
80. if musicPlaying:
81. pygame.mixer.music.stop()
82. else:
83. pygame.mixer.music.play(-1, 0.0)
84. musicPlaying = not musicPlaying
We will check if the user has pressed the M key. The M key will turn the background
music on or off. If
musicPlaying
is set to
True
, then that means the background music
is currently playing and we should stop the music by calling
pygame.mixer.music.stop()
. If
musicPlaying
is set to
False
, then that
means the background music is not currently playing and should be started by calling
pygame.mixer.music.play()
. The parameters we pass to the
pygame.mixer.music.play()
function are the same as we passed on line 40.
Finally, no matter what, we want to toggle the value in
musicPlaying
.
Toggling
a
boolean value means we set it to the opposite of its current value. The line
musicPlaying = not musicPlaying
will set the variable to
False
if it is
currently
True
or set it to
True
if it is currently
False
. Think of toggling as what
happens when you flip a light switch on or off.