In which we learn about handling sound and music in Panda
For the most part, dealing with sound and music is pretty simple in Panda3D. You load a sound- or music- file, you play it (perhaps after setting its volume, or telling it to loop), and that’s about it!
There are more complex things that can be done (such as using 3D positional sound), but for our purposes, the above will suffice.
One thing that’s worth noting is that Panda distinguishes between sound effects and music; it has separate manager-objects for them. This makes it easy to work with one of them as a whole, without affecting the other. For example, you can adjust the overall volume of your game’s music, leaving its sound effects unchanged–useful for “sound” and “music” volume-sliders in an options menu.
To start with, let’s load and play some music. In a bigger project we might have multiple music-files, to be played under various circumstances (such as in menus, or when the game ends), but for tutorial purposes we’re just going to have a single piece of music.
You should now hear music as you play!
You may recall that, in order to loop an animation in an Actor, we just call “loop”. Note, then, that this isn’t the case for sounds: instead, we first call “setLoop”, which doesn’t start the sound, but does indicate that it should loop when played, and then call “play”, which starts it.
Next, a simple sound-effect. Specifically, we’re going to have a sound play whenever an enemy spawns:
And that’s it. You should now hear a sound-effect whenever an enemy spawns.
With the procedure covered, let’s quickly add similar sound-effects for:
The laser hitting something
The laser hitting nothing
Walking Enemies attacking
Walking Enemies dying
And Traps hitting something
For most of this, we’ll move over to “GameObject.py”.
Some of our logic will want to check the status of a given sound, and the status-codes for this are stored in the “AudioSound” class, so we’ll import that:
Then we start adding, looping, and playing sounds. There’s a fair bit of this, but it’s all pretty simple, and is based on what we just did, so I’ll just provide you with the code:
We’re not quite done yet–but almost. We aren’t currently using the sounds that we loaded for the Trap Enemies hitting something, or stopping. That logic we’ll put in our collision methods, back in “Game.py”:
Now we’re done! When we play, we should now hear a variety of sounds, including the hum of our laser, the metallic “sikt!” of a Walking Enemy’s blades, the boom of Trap Enemies hitting walls, and so on.
This is starting to look almost like a complete game. But there are two major things missing: a way to restart the game after the player loses, and a main menu to present at the game’s start…