Quick answer: Call pygame.mixer.pre_init(44100, -16, 2, 1024) before pygame.init(). Standardize all audio files at 44.1 kHz. Larger buffer = less crackle, slight latency increase.
A platformer’s sound effects crackle when several play at once. Music plays with audible artifacts. Buffer underruns somewhere. The mixer’s default settings don’t match the audio files.
Mixer Init Parameters
pygame.mixer.init / pre_init takes:
- frequency: sample rate (Hz). Standard: 44100 or 48000.
- size: sample bit depth. -16 = signed 16-bit (most common).
- channels: 1 (mono) or 2 (stereo).
- buffer: samples per buffer. 512–2048. Smaller = lower latency but more crackle risk.
The Fix
import pygame
# Set mixer params BEFORE pygame.init
pygame.mixer.pre_init(
frequency=44100,
size=-16,
channels=2,
buffer=1024
)
pygame.init()
# Verify what we got
print(pygame.mixer.get_init()) # (44100, -16, 2)
pre_init must run before init. After init, the mixer is locked — can’t change params without quit/re-init.
Frequency Mismatch Symptoms
- Mixer 22050, files 44100: sounds play at half speed, pitched down by an octave.
- Mixer 48000, files 44100: sounds play slightly slow.
Standardize. Use 44100 for the mixer and ensure all WAV/OGG files use 44100 (audacity export setting).
Buffer Size Trade-off
Buffer is the number of samples per audio update cycle:
- 512: ~12ms latency at 44100 Hz. Crackle on busy CPUs.
- 1024: ~23ms. Good balance.
- 2048: ~46ms. Safe but audible latency on rhythm action.
If crackles persist, raise buffer. Music players: 2048 is fine. Latency-critical games: 512 with careful CPU management.
Verifying
Play several overlapping sounds. No crackle. Music plays at correct pitch. mixer.get_init() returns what you set.
“Mixer freq matches file freq. pre_init before pygame.init. Buffer 1024 for forgiving default.”
Standardize file freq in your asset pipeline — audacity batch-convert any 48 kHz incoming files to 44.1 kHz.