Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 41 ยท Sound and Input

Sound Effects and Music in Pygame

Learn pygame.mixer: load sound effects, stream background music, control volume and channels, handle end-of-music events and build a small sound manager.

A game without sound feels strangely empty. A short click when you press a button, a thud when a ball hits a wall and a looping track in the background make the same game feel far more alive. Pygame handles audio through the pygame.mixer module, which is started for you by pygame.init().

This lesson explains the two ways to play audio, how channels work, how to control volume and fades, and how to organize your sounds in a small manager class. Pygame needs a real sound card to play audio, so the examples in this lesson that use pygame.mixer are shown as read-only code, and each one is paired with a runnable stand-in that you can experiment with in the browser.

Two kinds of audio: Sound and music

Pygame separates audio into two tools, because short effects and long songs have different needs.

pygame.mixer.Sound pygame.mixer.music
Best for short effects (jump, coin, explosion) one long background track
Loaded fully into memory streamed from disk
At once many (one per channel) exactly one
Formats WAV, OGG (MP3 on most builds) OGG, MP3, WAV, others

A Sound object is decoded once and then can be played again instantly, as many times as you like. The music module decodes a little at a time while playing, so a five-minute song does not eat your memory.

flowchart LR
  F1["jump.wav"] --> S1["Sound object<br/>(in memory)"]
  F2["coin.ogg"] --> S2["Sound object<br/>(in memory)"]
  S1 --> CH["Mixer channels<br/>(default: 8)"]
  S2 --> CH
  F3["theme.ogg"] --> M["music stream<br/>(one track)"]
  CH --> OUT["Speakers"]
  M --> OUT

Sound effects share the mixer channels; the music stream plays beside them.

Playing a sound effect

Python
import pygame

pygame.mixer.pre_init(44100, -16, 2, 512)  # before pygame.init()
pygame.init()

jump = pygame.mixer.Sound("assets/jump.wav")   # load ONCE, not every frame
jump.set_volume(0.6)                           # 0.0 to 1.0

# later, inside the event loop
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
        jump.play()

Three details matter here.

  1. Load once. Reading a file from disk takes milliseconds, which would cause a visible hiccup if you did it inside the loop. Create your Sound objects before the loop starts.
  2. pre_init shrinks latency. The default buffer of 4096 samples can delay a sound by about a tenth of a second. A buffer of 512 reacts faster. Call pygame.mixer.pre_init before pygame.init().
  3. play() returns a channel. You can keep it and control that single playback.
Python
channel = explosion.play()          # a pygame.mixer.Channel (or None if all are busy)
if channel:
    channel.set_volume(1.0, 0.2)    # left speaker loud, right speaker quiet

Useful arguments of Sound.play(loops=0, maxtime=0, fade_ms=0): loops=2 plays three times in total, loops=-1 repeats forever, maxtime cuts the sound off after some milliseconds, and fade_ms fades it in.

Channels and what happens when they run out

The mixer has a fixed number of channels, 8 by default. Each Sound.play() takes a free channel. If all eight are busy, the call returns None and nothing is heard. For a busy shooter, raise the limit:

Python
pygame.mixer.set_num_channels(32)

You can also reserve a channel for something important, such as a voice line, so that sound effects never steal it:

Python
pygame.mixer.set_reserved(1)             # channel 0 is now yours alone
voice = pygame.mixer.Channel(0)
voice.play(announcer_sound)

A single Sound object can also be playing in several channels at once, which is exactly how a machine gun sound works. If you would rather not have overlapping copies of the same effect, call sound.stop() before sound.play().

Background music

Python
pygame.mixer.music.load("assets/theme.ogg")
pygame.mixer.music.set_volume(0.4)       # music usually sits below effects
pygame.mixer.music.play(-1)              # -1 means loop forever

pygame.mixer.music.pause()
pygame.mixer.music.unpause()
pygame.mixer.music.fadeout(1500)         # fade to silence in 1.5 s, then stop

Because only one track exists at a time, loading a new file replaces the old one. To change the soundtrack between levels, call fadeout, wait until it finishes and load the next file. You can ask Pygame to tell you when a track ends by registering an event:

Python
MUSIC_END = pygame.USEREVENT + 1
pygame.mixer.music.set_endevent(MUSIC_END)

# in the loop
if event.type == MUSIC_END:
    play_next_track()

pygame.mixer.music.queue("next.ogg") is a lighter alternative: it plays the queued file as soon as the current one finishes, with no gap.

Try it: a sound manager (stand-in)

Real audio cannot play here, so this stand-in implements the same idea the mixer uses: a limited pool of channels, a per-sound volume and a master volume. It has no pygame import, but the logic is what a real manager would wrap around pygame.mixer.

Python A tiny mixer with channel limits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Run it, then change channels=3 to channels=8 and notice that nothing is dropped. This is the exact behavior behind pygame.mixer.set_num_channels.

Try it: generate a beep as a WAV file

A WAV file is simply a header plus raw sample numbers. Python's standard library can build one with wave, and Pygame can load such a thing from bytes with pygame.mixer.Sound(buffer=...). This is handy for placeholder effects before you have real assets.

Python Build a beep in memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The byte count follows the formula samples x 2 bytes + 44 header bytes. Doubling the sample rate doubles the file.

A sound manager class

Most games grow a small helper so that the rest of the code can write sounds.play("coin") and never think about files.

Python
import pygame

class Sounds:
    def __init__(self):
        self.effects = {}
        self.muted = False

    def load(self, name, path, volume=1.0):
        sound = pygame.mixer.Sound(path)
        sound.set_volume(volume)
        self.effects[name] = sound

    def play(self, name):
        if not self.muted and name in self.effects:
            self.effects[name].play()

    def toggle_mute(self):
        self.muted = not self.muted
        pygame.mixer.music.set_volume(0 if self.muted else 0.4)

Add a mute key (traditionally M) because players often want quiet.

Common problems

  • pygame.error: mixer not initialized: you called a mixer function before pygame.init() or pygame.mixer.init().
  • No sound on a server or laptop without audio: the mixer fails to start. Wrap pygame.mixer.init() in try/except pygame.error and let the game run silently.
  • MP3 stutters or will not load: prefer OGG for music and WAV or OGG for effects. They work on every platform and in the browser.
  • Sound plays late: lower the buffer with pre_init, and keep effects short with no silence at the start.
  • Effects drown the music: set music volume to 0.3 to 0.5 and tune effects separately.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which tool should you use for a three-second explosion that may play many times at once?

    Sound objects are loaded into memory and can play on several channels at the same moment. The music module handles only one streamed track.
  2. 2. What does pygame.mixer.music.play(-1) do?

    The argument is the number of extra repeats; -1 means repeat without end.
  3. 3. A Sound.play() call returns None. What is the most likely reason?

    When no free channel exists the sound is not played and None is returned. Raise the limit with set_num_channels.
  4. 4. Why should Sound objects be created before the game loop?

    File reading and decoding take noticeable time. Loading once and replaying the object is instant.

Summary

  • Use Sound for short effects and mixer.music for one streamed background track.
  • Load sounds once, play them many times, and set volume between 0.0 and 1.0.
  • The mixer has 8 channels by default; raise it with set_num_channels or reserve one with set_reserved.
  • music.set_endevent, queue and fadeout help you chain tracks smoothly.
  • Prefer OGG/WAV, call pre_init for low latency and give players a mute key.

Next: Input Maps, Held Keys and Mouse Dragging