pygame.mixer
Load and play sound effects, control channels and volume, and stream background music with pygame.mixer.music.
On this page
Overview#
pygame.mixer plays audio. pygame.mixer.Sound holds a whole effect in memory and plays it on one of several channels at once. pygame.mixer.music streams a single long track from disk. pygame.init() initialises the mixer with default settings; call pygame.mixer.pre_init() before it to change them.
Syntax#
pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=512)
pygame.init()
sound = pygame.mixer.Sound("jump.ogg")
channel = sound.play(loops=0, maxtime=0, fade_ms=0)
pygame.mixer.music.load("theme.ogg")
pygame.mixer.music.play(loops=-1, start=0.0, fade_ms=0)Initialisation parameters#
| Parameter | Meaning |
|---|---|
frequency | Sample rate in Hz (44100 is CD quality). |
size | Bits per sample; negative means signed. -16 is the usual choice. |
channels | 1 mono, 2 stereo. |
buffer | Samples per audio buffer. Smaller means lower latency but risks crackling. 512 is the default in Pygame 2. |
pygame.mixer.get_init() returns (frequency, format, channels), or None if the mixer isn't running.
Sound#
| Method | Meaning |
|---|---|
Sound(file) or Sound(buffer=bytes_like) | Load from a file (WAV, OGG, MP3 in most builds) or raw samples. |
play(loops=0, maxtime=0, fade_ms=0) | Plays on a free channel; returns that Channel, or None if none was free. loops=-1 repeats forever. |
stop(), fadeout(ms) | Stop on all channels. |
set_volume(v), get_volume() | 0.0 to 1.0. |
get_length() | Length in seconds. |
Channel#
| Method | Meaning |
|---|---|
pygame.mixer.Channel(index) | A specific channel. |
play(sound), queue(sound) | Play now, or after the current sound. |
set_volume(v) or set_volume(left, right) | Volume, or stereo panning with two values. |
get_busy(), pause(), unpause(), stop() | Control. |
Module functions: set_num_channels(n), get_num_channels(), set_reserved(n) (keep the first n channels for manual use), find_channel(), and stop(), pause(), unpause(), fadeout(ms) for everything.
pygame.mixer.music#
| Function | Meaning |
|---|---|
load(file) | Load a track (replaces the current one). |
play(loops=0, start=0.0, fade_ms=0) | loops=-1 repeats forever. |
pause(), unpause(), stop(), fadeout(ms) | Control. |
set_volume(v), get_volume() | 0.0 to 1.0. |
get_busy() | True while playing. |
queue(file) | Play another file after the current one. |
set_endevent(type) | Post an event when the track ends. |
Practical example#
"""pygame.mixer: initialise audio, play a Sound on channels, adjust volume and stereo panning."""
import array
import math
import pygame
pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=512)
pygame.init()
screen = pygame.display.set_mode((480, 200))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 26)
freq, size, channels = pygame.mixer.get_init()
# Build a short beep directly from samples (16-bit signed, interleaved stereo).
samples = array.array("h")
for i in range(int(freq * 0.15)):
v = int(12000 * math.sin(2 * math.pi * 660 * i / freq) * (1 - i / (freq * 0.15)))
samples.extend([v] * channels)
beep = pygame.mixer.Sound(buffer=samples)
print("Beep length:", round(beep.get_length(), 3), "s")
pygame.mixer.set_num_channels(8)
pan = 0.5 # 0.0 = left speaker, 1.0 = right speaker
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_SPACE:
channel = beep.play() # returns the Channel or None
if channel:
channel.set_volume(1 - pan, pan) # left, right volume
elif event.key == pygame.K_LEFT:
pan = max(0.0, pan - 0.25)
elif event.key == pygame.K_RIGHT:
pan = min(1.0, pan + 0.25)
screen.fill((20, 26, 46))
screen.blit(font.render("Space: beep Left/Right: pan", True, (230, 236, 247)), (20, 40))
screen.blit(font.render(f"Pan {pan:.2f} mixer {freq} Hz, {channels} channels", True, (244, 197, 49)), (20, 80))
pygame.display.flip()
clock.tick(60)
pygame.quit()The beep is generated from samples, so no file is needed. Space plays it; the arrow keys pan it between speakers.
Common errors#
pygame.error: mixer not initialized: no audio device could be opened (common on servers, in some virtual machines and in WSL). Wrap audio intry/except pygame.errorso the game runs silently. See no sound.- Delay before sounds: lower the buffer with
pre_initbeforepygame.init(). - Sounds cut off when many play: all channels are busy. Increase
set_num_channels. pygame.error: Unrecognized audio format: convert the file to OGG or 16-bit WAV.