Enhancing Your Game With Sound Effects
00:00 In the previous lesson, your game got one step closer to being an Asteroids clone. It now has collisions and different rock sizes. In this lesson, you’ll add some polish by including some sound.
00:12 Pygame pretty much takes care of the hard parts of sound. It abstracts away dealing with the operating system and provides methods for playing loaded files.
Sound files are assets and, like sprites, can be loaded into the system using utility methods. This is
utils.py. Remember it? It’s been a while since you’ve been in here.
The key to using sound is the
Sound object from Pygame’s mixer module. With it imported in, you just need to get the path to your sound file, then create a new object with it. Like loading a sprite from way back when, this path assumes that sounds are found in the
Sounds will live in their own folder there, called
sounds/, and are assumed to be
.wav files. Path in hand, create the object and return it. This is so small, it almost isn’t worth a utility method, but using the utility method means you don’t have to remember the relative path logic everywhere in your code wherein you’re loading a sound file.
Now, let’s use the sound. This is
models.py. First, you’ll need to import the newly written
load_sound() from the
Let me scroll down to the
.pew_pew attribute of
Spaceship stores the sound of your space bullets firing, using the recently written
load_sound() utility function. Now, all that is left to do is make the noise. Inside of the
.shoot() method, call the
.play() method on the
.pew_pew sound and you’re all good.
01:46 It’s almost disappointing. I was having fun making the noises myself.
01:54 And look at that. THX surround sound it is not, but your game is making some noise.
02:04 Only two lessons left. In the second-to-last one, I’ll show you how to display info to the user with text on the screen.
Become a Member to join the conversation.