Welcome back!
So far, we have created a simple game where:
- The player moves using the keyboard.
- The enemy moves automatically.
- The player collects coins.
- The score increases.
- A Game Over screen appears when the enemy catches the player.
Our game looks good. But something is still missing. Imagine collecting a coin and hearing nothing. Or imagine losing the game without any sound. It doesn’t feel exciting.
Today, we will make our game come alive by adding sound effects and background music. By the end of this lesson, your game will sound much more like a real game.
What Will You Learn?
After completing this lesson, you will know:
- How to add sound effects in Pygame
- How to play background music
- How to play a coin collection sound
- How to play a Game Over sound
- How to control the volume
Step 1: Create a Sounds Folder
Inside your project folder, create a new folder.
Lesson15
│
├── lesson15_sound.py
│
├── images
│
└── sounds
│
├── coin.wav
├── game_over.wav
└── background.mp3
Keeping sounds in one folder makes your project neat and organized.
Step 2: Initialize the Mixer
Pygame uses the Mixer module to play sounds.
Add this line after pygame.init().
pygame.mixer.init()
Now your game is ready to play audio.
Step 3: Load the Sounds
Add these lines after loading your images.
coin_sound = pygame.mixer.Sound("sounds/coin.wav")
game_over_sound = pygame.mixer.Sound("sounds/game_over.wav")
These sounds are stored in memory and are ready to play.
Step 4: Play Background Music
Load the music.
pygame.mixer.music.load("sounds/background.mp3")
Start the music.
pygame.mixer.music.play(-1)
The value -1 means the music will repeat forever.
Step 5: Set the Volume
Sometimes the music is too loud.
You can control it.
pygame.mixer.music.set_volume(0.4)
The volume ranges from:
0.0 = Mute
1.0 = Maximum Volume
Step 6: Play the Coin Sound
Find this code.
if player_rect.colliderect(coin_rect):
Add:
coin_sound.play()
The code becomes:
if player_rect.colliderect(coin_rect):
coin_sound.play()
score += 1
coin_x = random.randint(0,736)
coin_y = random.randint(0,536)
Now every collected coin plays a sound.
Step 7: Play the Game Over Sound
Find:
game_over = True
Replace it with:
game_over_sound.play()
pygame.mixer.music.stop()
game_over = True
Now:
- Background music stops.
- Game Over sound plays.
This creates a much better experience.
Complete Program
Note: This complete program is based on the previous lesson. Only the new sound-related code has been added.
import pygame
import random
pygame.init()
pygame.mixer.init()
# -------------------------
# Create Window
# -------------------------
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Pygame Sound Effects")
# -------------------------
# Load Images
# -------------------------
background = pygame.image.load("images/background.png")
player = pygame.image.load("images/player.png")
enemy = pygame.image.load("images/enemy.png")
coin = pygame.image.load("images/coin.png")
# -------------------------
# Load Sounds
# -------------------------
coin_sound = pygame.mixer.Sound("sounds/coin.wav")
game_over_sound = pygame.mixer.Sound("sounds/game_over.wav")
pygame.mixer.music.load("sounds/background.mp3")
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)
# -------------------------
# Fonts
# -------------------------
font = pygame.font.Font(None,36)
game_over_font = pygame.font.Font(None,72)
# -------------------------
# Player
# -------------------------
player_x = 350
player_y = 250
player_speed = 5
# -------------------------
# Enemy
# -------------------------
enemy_x = 0
enemy_y = 100
enemy_speed = 3
# -------------------------
# Coin
# -------------------------
coin_x = random.randint(0,736)
coin_y = random.randint(0,536)
# -------------------------
# Score
# -------------------------
score = 0
game_over = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if not game_over:
screen.blit(background,(0,0))
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and player_x < 736:
player_x += player_speed
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= player_speed
if keys[pygame.K_UP] and player_y > 0:
player_y -= player_speed
if keys[pygame.K_DOWN] and player_y < 536:
player_y += player_speed
enemy_x += enemy_speed
if enemy_x > 800:
enemy_x = -64
player_rect = player.get_rect(topleft=(player_x,player_y))
enemy_rect = enemy.get_rect(topleft=(enemy_x,enemy_y))
coin_rect = coin.get_rect(topleft=(coin_x,coin_y))
# Coin Collision
if player_rect.colliderect(coin_rect):
coin_sound.play()
score += 1
coin_x = random.randint(0,736)
coin_y = random.randint(0,536)
# Enemy Collision
if player_rect.colliderect(enemy_rect):
game_over_sound.play()
pygame.mixer.music.stop()
game_over = True
screen.blit(player,(player_x,player_y))
screen.blit(enemy,(enemy_x,enemy_y))
screen.blit(coin,(coin_x,coin_y))
score_text = font.render(
"Score : " + str(score),
True,
(255,255,255)
)
screen.blit(score_text,(10,10))
else:
screen.fill((25,25,25))
game_text = game_over_font.render(
"GAME OVER",
True,
(255,0,0)
)
score_text = font.render(
"Final Score : " + str(score),
True,
(255,255,255)
)
screen.blit(game_text,(200,180))
screen.blit(score_text,(290,280))
pygame.display.update()
pygame.quit()
Let’s Understand the New Code
Today we learned only a few new functions:
pygame.mixer.init()
Starts the sound system.
pygame.mixer.Sound()
Loads a sound effect.
sound.play()
Plays a sound one time.
pygame.mixer.music.load()
Loads background music.
pygame.mixer.music.play(-1)
Plays the music continuously.
pygame.mixer.music.stop()
Stops the background music.
These six functions are enough to add sound to many beginner games.
Homework
Try these activities on your own.
Activity 1
Replace the coin sound with another sound.
Activity 2
Reduce the music volume to:
0.2
How does the game feel now?
Activity 3
Increase the music volume to:
0.8
Which volume do you like more?
Common Mistakes
Sound is not playing
Check that the sound file exists in the sounds folder and the file name matches exactly.
Music starts but never stops
Make sure you call:
pygame.mixer.music.stop()
when the game ends.
Error: Mixer not initialized
Always call:
pygame.mixer.init()
before loading any sounds.
What You Learned Today
Today you learned:
- How to add sound effects in Pygame
- How to play background music
- How to play a coin collection sound
- How to play a Game Over sound
- How to control music volume
Frequently Asked Questions
How do I add sound effects in Pygame?
Use pygame.mixer.Sound() to load a sound file and call .play() when an event occurs.
How do I play background music in Pygame?
Load the music with pygame.mixer.music.load() and start it using pygame.mixer.music.play(-1) for continuous playback.
Which audio formats does Pygame support?
Pygame commonly supports WAV, MP3, and OGG files, depending on your installation and platform.
Why is my sound not working in Pygame?
Check that the mixer is initialized, the file path is correct, and the sound file exists.
Can I play multiple sounds at the same time?
Yes. Background music and short sound effects can play together, making your game more engaging.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
Shubhranshu Shekhar is a coding instructor, mentor, and founder of VSIT Delhi with 20+ years of teaching experience (since 2004). He has guided many students who are now working in multinational companies and specializes in Full Stack Development, Python, Digital Marketing, and Data Analytics.
