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

Unlock This Lesson

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

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

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.

00:21 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.

00:33 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 assets/ subdirectory.

00:50 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.

01:15 Now, let’s use the sound. This is models.py. First, you’ll need to import the newly written load_sound() from the utils file.

01:24 Let me scroll down to the Spaceship. 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.