What is SDL2_mixer?
SDL2_mixer is the standard multi-channel audio mixer library for SDL2. It sits on top of SDL2's audio subsystem and provides two independent audio layers that work simultaneously:
- Music — one background stream at a time. Supports full decoding of OGG, MP3, FLAC, MOD, MIDI, OPUS, AIFF, and WAV. Perfect for continuous background tracks.
- Chunks — up to 32 simultaneous short-sample channels. Typically used for sound effects (footsteps, explosions, UI clicks). Each channel can be independently paused, faded, and spatially positioned.
Both layers share the same SDL2 audio device opened via Init or InitDefault. You must call SDL_Init(SDL_INIT_AUDIO) (from the sdl2 package) before initializing the mixer.
Audio Formats
| Format | Extension(s) | Notes |
|---|---|---|
| WAV | .wav | Uncompressed PCM, 8/16/32-bit, mono/stereo. Fastest to decode. |
| OGG | .ogg | Ogg Vorbis compressed (libvorbis). Best for music & long effects. |
| MP3 | .mp3 | MPEG Layer 3 (dr_mp3 / libmpg123). Wide compatibility. |
| FLAC | .flac | Lossless compression. High quality, larger files. |
| MOD | .mod .xm .s3m .it | Tracker/chiptune music via libmikmod or libxmp. Tiny file sizes. |
| OPUS | .opus | Opus codec. Excellent quality at low bitrates. |
| MIDI | .mid .midi | MIDI playback via FluidSynth or Timidity. Needs soundfont. |
| AIFF | .aif .aiff | Apple AIFF uncompressed. Common on macOS. |
Music vs Chunks
Music is a single decoded stream — only one music track plays at a time. Use it for looping background music that runs the entire game session. It supports all formats and can be paused, faded, and seeked.
Chunks are pre-loaded audio buffers played on numbered channels. You allocate channels (default 8, up to 32) and play chunks on free channels. Use them for short sound effects: footsteps, weapon fire, coin pickups, UI clicks, explosions.
Typical game setup: 1 music track + 8–32 chunk channels. Each chunk channel independently supports volume, pause/resume, fade-in/fade-out, timed expiry, and 3D positional audio.
Types
| Type | Description |
|---|---|
| TMixChunk | Handle to a loaded sound effect chunk (Integer). Returned by LoadWAV / LoadWAVFromMemory. |
| TMixMusic | Handle to a loaded music stream (Integer). Returned by LoadMusic. |
| TMixMusicType | Enum: mmtNone, mmtCMD, mmtWAV, mmtMOD, mmtMIDI, mmtOGG, mmtMP3, mmtFLAC, mmtOpus |
| TMixFading | Enum: mfNone (not fading), mfOut (fading out), mfIn (fading in) |
API Reference
Init
| Function | Description |
|---|---|
| Init(Frequency, Format, Channels, ChunkSize): Boolean | Open the audio device. Typical values: 44100 Hz, stereo (2), chunk 2048. |
| InitDefault: Boolean | Open with defaults: 44100 Hz, stereo, 2048 chunk size. |
| Quit | Close the audio device and shut down the mixer. |
| Version: string | Return the SDL2_mixer library version string. |
Channels
| Function | Description |
|---|---|
| AllocateChannels(NumChannels): Integer | Set the number of mixing channels (default 8). Returns the actual count allocated. |
| Volume(Channel, Vol): Integer | Set volume 0–128 for a channel. Pass -1 to set all channels. Returns previous volume. |
| Pause(Channel) | Pause a channel. -1 pauses all channels. |
| Resume(Channel) | Resume a paused channel. -1 resumes all channels. |
| HaltChannel(Channel) | Immediately stop a channel. -1 stops all channels. |
| ExpireChannel(Channel, Ms) | Stop a channel after Ms milliseconds. |
| FadeOutChannel(Channel, Ms) | Fade out and stop a channel over Ms milliseconds. |
| Playing(Channel): Boolean | Returns True if the channel is currently playing. |
| Paused(Channel): Boolean | Returns True if the channel is currently paused. |
Chunks (Sound Effects)
| Function | Description |
|---|---|
| LoadWAV(Path): TMixChunk | Load a sound effect from file (WAV, OGG, or any supported format). |
| LoadWAVFromMemory(Data): TMixChunk | Load a chunk from an in-memory buffer (string of bytes). |
| FreeChunk(Chunk) | Free a loaded chunk and release its memory. |
| VolumeChunk(Chunk, Vol): Integer | Set the default volume for a chunk (0–128). Applied on every PlayChannel call. |
| PlayChannel(Channel, Chunk, Loops): Integer | Play chunk on channel (-1 = first free). Loops: 0 = once, -1 = infinite. Returns channel used. |
| FadeInChannel(Channel, Chunk, Loops, Ms): Integer | Play with fade-in over Ms milliseconds. Returns channel used. |
Music (Background)
| Function | Description |
|---|---|
| LoadMusic(Path): TMixMusic | Load music from file (WAV, OGG, MP3, FLAC, MOD, MIDI, OPUS, AIFF). |
| FreeMusic(Music) | Free a loaded music handle. |
| PlayMusic(Music, Loops) | Play music. Loops: -1 = infinite, 0 = once, N = N times. |
| FadeInMusic(Music, Loops, Ms) | Start music with a fade-in over Ms milliseconds. |
| FadeOutMusic(Ms) | Fade out the currently playing music over Ms milliseconds. |
| PauseMusic | Pause the music stream. |
| ResumeMusic | Resume a paused music stream. |
| HaltMusic | Immediately stop the music stream. |
| VolumeMusic(Vol): Integer | Set music volume 0–128. Returns previous volume. |
| PlayingMusic: Boolean | Returns True if music is currently playing (not halted). |
| PausedMusic: Boolean | Returns True if music is paused. |
| FadingMusic: TMixFading | Returns mfNone, mfIn, or mfOut depending on current fade state. |
| MusicType(Music): TMixMusicType | Returns the detected format type of a loaded music handle. |
| MusicTitle(Music): string | Returns the title metadata tag of the music file, if any. |
| MusicDuration(Music): Double | Returns the duration of the music in seconds. |
| SetMusicPosition(Pos) | Seek to position in seconds (OGG, MP3, FLAC, MOD). |
Positional Audio
| Function | Description |
|---|---|
| SetPanning(Channel, Left, Right) | Left/right balance for a channel. Left and Right each 0–255. 255/255 = center. |
| SetDistance(Channel, Distance) | Distance attenuation: 0 = near (full volume), 255 = far (silent). |
| SetPosition(Channel, Angle, Distance) | Full 3D position: Angle 0–360 degrees (0 = front), Distance 0–255. |
Code Example — Game Audio Setup
uses sdl2_mixer;
var
Music: TMixMusic;
SfxJump, SfxCoin: TMixChunk;
Ch: Integer;
begin
{ SDL_Init(SDL_INIT_AUDIO) must be called first }
InitDefault; { 44100Hz, stereo, 2048 chunk }
AllocateChannels(16);
{ Load background music }
Music := LoadMusic('assets/bgm.ogg');
PlayMusic(Music, -1); { loop forever }
VolumeMusic(64); { 50% volume }
{ Load sound effects }
SfxJump := LoadWAV('assets/jump.wav');
SfxCoin := LoadWAV('assets/coin.wav');
VolumeChunk(SfxJump, 100);
{ Play on first free channel }
Ch := PlayChannel(-1, SfxJump, 0);
{ 3D positional audio }
SetPosition(Ch, 45, 128); { 45 degrees, medium distance }
{ Cleanup }
FreeChunk(SfxJump);
FreeChunk(SfxCoin);
FreeMusic(Music);
Quit;
end.
MOD / Tracker Music
SDL2_mixer can play classic tracker music formats — .mod, .xm, .s3m, .it — via the libmikmod or libxmp backend. Tracker files are ideal for retro games and small indie projects: a complete multi-channel song often fits in 50–200 KB (versus several MB for OGG). Just call LoadMusic with the tracker file path and the format is detected automatically.
Fade In — Scene Transition
{ Smooth music transition between scenes }
FadeOutMusic(1500); { fade out current track over 1.5s }
var NextTrack := LoadMusic('assets/boss.ogg');
FadeInMusic(NextTrack, -1, 2000); { fade in new track over 2s }
{ Timed sound effect expiry }
var Ch := PlayChannel(-1, SfxAlarm, -1); { loop alarm }
ExpireChannel(Ch, 5000); { auto-stop after 5 seconds }
FadeOutChannel(Ch, 1000); { also fade it out over 1s }
3D Positional Audio
{ Player at origin, enemy to the right at medium distance }
var Ch := PlayChannel(-1, SfxFootstep, 0);
SetPosition(Ch, 90, 80); { 90 degrees = right, distance 80 }
{ Stereo panning — hard left }
var Ch2 := PlayChannel(-1, SfxUI, 0);
SetPanning(Ch2, 255, 0); { full left channel only }
{ Distance fade (no directional info) }
var Ch3 := PlayChannel(-1, SfxExplosion, 0);
SetDistance(Ch3, 200); { almost silent — very far away }
Install
ppm install sdl2-mixer
sudo apt install libsdl2-mixer-dev
Package Info
Requirement
Requires SDL2 initialized with SDL_INIT_AUDIO before calling Init or InitDefault.
Functions
- Init / InitDefault
- Quit / Version
- AllocateChannels
- Volume / Pause / Resume
- HaltChannel / ExpireChannel
- FadeOutChannel
- Playing / Paused
- LoadWAV / LoadWAVFromMemory
- FreeChunk / VolumeChunk
- PlayChannel / FadeInChannel
- LoadMusic / FreeMusic
- PlayMusic / FadeInMusic
- FadeOutMusic / HaltMusic
- PauseMusic / ResumeMusic
- VolumeMusic
- PlayingMusic / PausedMusic
- FadingMusic / MusicType
- MusicTitle / MusicDuration
- SetMusicPosition
- SetPanning / SetDistance
- SetPosition
- GetError
See Also
- sdl2 — window & renderer
- sdl2-image — PNG/JPG loading
- portaudio — low-level audio I/O
- libsndfile — audio file decoding
- opus — Opus codec