Sound and music

Play sound effects with pygame.mixer.Sound, stream background music with pygame.mixer.music, control volume, and avoid the usual audio delays and errors.

Intermediate3 min readUpdated
On this page

What you'll learn

  • The difference between mixer.Sound and mixer.music
  • Which audio formats to use
  • Volume, looping, pausing and channels
  • Reducing the delay between an action and its sound

Prerequisites: Keyboard input.

Two tools for two jobs#

pygame.mixer.Soundpygame.mixer.music
Use forshort effects: jumps, coins, explosionsone long background track
Loadingthe whole file is decoded into memorystreamed from disk while playing
How many at oncemany, one per channelone track at a time
Typical formatsWAV, OGGOGG, MP3, WAV

Effects are played many times and need to start instantly, so they live in memory. Music can be several minutes long, so it streams.

A working example#

You don't need any audio files for this example: it writes three small WAV files using only Python's standard library the first time it runs, then plays them.

sound_basics.pyDownload
"""Sound effects and music. The sounds are generated as WAV files the first time you run this."""
import math
import struct
import wave
from pathlib import Path

import pygame

HERE = Path(__file__).parent
SAMPLE_RATE = 44100


def write_tone(path, notes, volume=0.4):
    """Write a mono 16-bit WAV made of (frequency, seconds) notes using only the standard library."""
    frames = bytearray()
    for freq, seconds in notes:
        count = int(SAMPLE_RATE * seconds)
        for i in range(count):
            envelope = min(1.0, i / 400, (count - i) / 400)          # avoid clicks
            sample = math.sin(2 * math.pi * freq * i / SAMPLE_RATE) if freq else 0.0
            frames += struct.pack("<h", int(sample * envelope * volume * 32767))
    with wave.open(str(path), "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(SAMPLE_RATE)
        w.writeframes(bytes(frames))


jump_wav = HERE / "jump.wav"
coin_wav = HERE / "coin.wav"
music_wav = HERE / "music_loop.wav"
if not jump_wav.exists():
    write_tone(jump_wav, [(330, 0.05), (440, 0.05), (660, 0.08)])
if not coin_wav.exists():
    write_tone(coin_wav, [(988, 0.06), (1319, 0.18)])
if not music_wav.exists():
    melody = [(262, .25), (330, .25), (392, .25), (523, .25), (392, .25), (330, .25), (294, .5)]
    write_tone(music_wav, melody * 2, volume=0.15)

pygame.mixer.pre_init(44100, -16, 2, 512)    # small buffer = low latency for effects
pygame.init()
screen = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 28)

jump_sound = pygame.mixer.Sound(jump_wav)
coin_sound = pygame.mixer.Sound(coin_wav)
coin_sound.set_volume(0.6)
pygame.mixer.music.load(music_wav)
pygame.mixer.music.set_volume(0.5)
pygame.mixer.music.play(loops=-1)            # -1 repeats forever
muted = False

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_j:
                jump_sound.play()
            elif event.key == pygame.K_c:
                coin_sound.play()
            elif event.key == pygame.K_m:
                muted = not muted
                pygame.mixer.music.set_volume(0 if muted else 0.5)
            elif event.key == pygame.K_p:
                if pygame.mixer.music.get_busy():
                    pygame.mixer.music.pause()
                else:
                    pygame.mixer.music.unpause()

    screen.fill((20, 26, 46))
    lines = ["J: jump sound   C: coin sound", "M: mute music   P: pause/resume music",
             f"Music {'muted' if muted else 'on'} | channels busy: {sum(pygame.mixer.Channel(i).get_busy() for i in range(pygame.mixer.get_num_channels()))}"]
    for i, line in enumerate(lines):
        screen.blit(font.render(line, True, (230, 236, 247)), (30, 40 + i * 40))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Press J and C for effects, M to mute the music and P to pause it.

Key calls:

  • pygame.mixer.Sound(path) loads an effect; sound.play() plays it on a free channel and returns that Channel.
  • sound.set_volume(0.6) sets the volume from 0.0 to 1.0 for that sound.
  • pygame.mixer.music.load(path) then pygame.mixer.music.play(loops=-1) loops background music forever.
  • pygame.mixer.music.pause(), unpause(), stop(), fadeout(ms) and set_volume() control the track.

Formats#

OGG Vorbis is the safest choice for both effects and music: compact, high quality and supported everywhere Pygame runs. WAV is fine for short effects. MP3 works with mixer.music in Pygame 2 on common platforms, but OGG avoids surprises. Free tools such as Audacity can convert between formats.

Reducing latency#

If sounds play noticeably after the action, the audio buffer is too large. Call pygame.mixer.pre_init() before pygame.init() with a smaller buffer:

Python
pygame.mixer.pre_init(44100, -16, 2, 512)   # frequency, size, channels, buffer
pygame.init()

512 samples is about 12 milliseconds at 44.1 kHz. Values that are too small can crackle on slow machines; 512 or 1024 are common choices.

Channels#

The mixer has 8 channels by default, so at most 8 effects play at once. When all are busy, play() returns None and the sound is skipped. Raise the limit with pygame.mixer.set_num_channels(16), or reserve a channel for important sounds:

Python
pygame.mixer.set_reserved(1)
voice_channel = pygame.mixer.Channel(0)
voice_channel.play(dialogue_sound)

channel.set_volume(left, right) pans a sound between speakers, as shown in the mixer reference.

Respecting the player#

Always provide a way to mute or lower volume, keep music quieter than effects, and remember the setting between sessions (see saving game data). In browsers, audio may stay silent until the player interacts with the page because of autoplay rules.

Common mistakes#

  • pygame.error: mixer not initialized: no audio device was found, or pygame.init() couldn't open it. Wrap audio setup in try/except so the game still runs silently. See no sound in Pygame.
  • Loading a Sound every time it plays adds delay and stutters. Load all effects once at startup.
  • Using mixer.music for effects: starting a new track stops the previous one.
  • Huge WAV music files: stream music with mixer.music, preferably as OGG.

Practice exercises#

  1. Add a sound to the Star Catcher game when a star is caught.
  2. Make a volume slider controlled by the Up and Down keys and show the value on screen.
  3. Fade the music out over two seconds when the game ends with pygame.mixer.music.fadeout(2000).
  4. Play the coin sound with slightly random volume so repeats sound less mechanical.
↑ ↓ to moveEnter to openEsc to close