How to Add Sound Effects to your Python Game

Enhance your Python games with sound effects using Pygame. This tutorial covers installing Pygame, loading sounds, and incorporating audio feedback into games like Flappy Bird.
  · 4 min read · Updated may 2024 · Game Development · Python for Multimedia

Before we get started, have you tried our new Python Code Assistant? It's like having an expert coder at your fingertips. Check it out!

Sound effects can significantly enhance the gaming experience by providing audio feedback for actions and events in the game. In this tutorial, we'll learn how to add sound effects to a Python game using the Pygame library.

Installation and Setup

Before we start, ensure you have Python and Pygame installed. If you haven't installed Pygame yet, you can do so using pip:

pip install pygame

Next, you can set up a basic Pygame window. If you already have a game setup, you can skip this step. For this tutorial, I am using the Flappy Bird game code from my previous article; you can check it if you want to get the code for the Flappy Bird game.

Basic Functions

Let's start by understanding how to load sounds to our Python game and how to play them.

# Load sound effect
hit = pygame.mixer.Sound('hit.wav')

# Play sound effect
hit.play()

The pygame.mixer lets us work with sounds and music in our game. To load a sound, you can use pygame.mixer.Sound() and specify the audio file name you want to load. You can also access .mp3 files using these. In playing your audio file, you can simply use .play() to play the sound just once by default but you can specify to the .play() method how many times you want it to play.

# load a ".mp3" sound effect
whoosh = pygame.mixer.Sound('whoosh.mp3')

# play sound effect 3 times
whoosh.play(3)

To load music, you can use pygame.mixer.music.load() and put the audio file name inside the method. To play it, you can use pygame.mixer.music.play(). Same with playing the sound, you can specify how many times you want to play music. If you want to play it on a loop, you simply put -1 inside the method.

# load music
pygame.mixer.music.load("assets/sfx/bgm.wav")

# play music on repeat
pygame.mixer.music.play(-1)

Setting up the volume for sound and music is also pretty similar using the set_volume() method, which takes a value between 0.0 (mute) and 1.0 (full volume).

# setting volume for sound
whoosh.set_volume(0.5)
hit.set_volume(0.7)

# setting volume for music
pygame.mixer.music.set_volume(0.8)

Using it in an Actual Working Game (Flappy Bird)

I modified my previous code of the Flappy Bird game. I added a sfx folder inside the assets folder and put there the audio files I'm gonna use.

Let's first add background music to our game. Let's place it inside our main() method inside the Main() class, above our game while loop:

# main.py
class Main:
    def __init__(self, screen):
        ...

    def main(self):
        # adding background music to the game
        pygame.mixer.music.load("assets/sfx/bgm.wav")
        pygame.mixer.music.set_volume(0.8)
        pygame.mixer.music.play(-1)

        world = World(screen)
        while True:
            ...

if __name__ == "__main__":
    play = Main(screen)
    play.main()

Next, let's add sound effects for each jump of the bird. I add the sound _jump() method in the Bird() class:

# bird.py
class Bird(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        ...

    def _animate(self):
        ...

    def _jump(self):
        self.direction.y = self.jump_move

        # adding jump sound effects
        whoosh = pygame.mixer.Sound("assets/sfx/whoosh.mp3")
        whoosh.set_volume(0.5)
        whoosh.play()

    def update(self, is_jump):
        ...

And lastly, we're adding a sound when the bird either hits the pipes, the ceiling of the game window or falls below the game window. Let's add it inside the _handle_colisions() method in World() class:

class World:
    def __init__(self, screen):
        ...

    def _generate_world(self):
        ...

    def _add_pipe(self):
        ...

    def _scroll_x(self):
        ...

    def _apply_gravity(self, player):
        ...

    def _handle_collisions(self):
        bird = self.player.sprite
        # for collision checking
        if pygame.sprite.groupcollide(self.player, self.pipes, False, False) or bird.rect.bottom >= HEIGHT or bird.rect.top <= 0:

            # add sound sound when hit pipes, ceiling or fell below
            if self.playing:
                hit = pygame.mixer.Sound("assets/sfx/hit.wav")
                hit.set_volume(0.7)
                hit.play()
                self.playing = False
            
            self.game_over = True

        # for scoring 
        else:
            ...

    def update(self, player_event = None):
        ...

Conclusion

And that's it! Adding sound effects to your Python game using Pygame is a great way to enhance the player's experience. By following this tutorial, you should be able to load, play, and control various sound effects and background music in your game. Experiment with different sounds and volumes to find the best fit for your game.

Check the complete code here.

Here are some games you can add sound effects to:

Finished reading? Keep the learning going with our AI-powered Code Explainer. Try it now!

View Full Code Improve My Code
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!