sdl2-mixer clib Multimedia

SDL2_mixer multi-channel audio — background music (WAV, OGG, MP3, FLAC, MOD, MIDI) and up to 32 simultaneous sound effect channels with 3D positional audio.

ppm install sdl2-mixer

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:

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

FormatExtension(s)Notes
WAV.wavUncompressed PCM, 8/16/32-bit, mono/stereo. Fastest to decode.
OGG.oggOgg Vorbis compressed (libvorbis). Best for music & long effects.
MP3.mp3MPEG Layer 3 (dr_mp3 / libmpg123). Wide compatibility.
FLAC.flacLossless compression. High quality, larger files.
MOD.mod .xm .s3m .itTracker/chiptune music via libmikmod or libxmp. Tiny file sizes.
OPUS.opusOpus codec. Excellent quality at low bitrates.
MIDI.mid .midiMIDI playback via FluidSynth or Timidity. Needs soundfont.
AIFF.aif .aiffApple AIFF uncompressed. Common on macOS.

Music vs Chunks

Two-layer audio model

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

TypeDescription
TMixChunkHandle to a loaded sound effect chunk (Integer). Returned by LoadWAV / LoadWAVFromMemory.
TMixMusicHandle to a loaded music stream (Integer). Returned by LoadMusic.
TMixMusicTypeEnum: mmtNone, mmtCMD, mmtWAV, mmtMOD, mmtMIDI, mmtOGG, mmtMP3, mmtFLAC, mmtOpus
TMixFadingEnum: mfNone (not fading), mfOut (fading out), mfIn (fading in)

API Reference

Init

FunctionDescription
Init(Frequency, Format, Channels, ChunkSize): BooleanOpen the audio device. Typical values: 44100 Hz, stereo (2), chunk 2048.
InitDefault: BooleanOpen with defaults: 44100 Hz, stereo, 2048 chunk size.
QuitClose the audio device and shut down the mixer.
Version: stringReturn the SDL2_mixer library version string.

Channels

FunctionDescription
AllocateChannels(NumChannels): IntegerSet the number of mixing channels (default 8). Returns the actual count allocated.
Volume(Channel, Vol): IntegerSet 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): BooleanReturns True if the channel is currently playing.
Paused(Channel): BooleanReturns True if the channel is currently paused.

Chunks (Sound Effects)

FunctionDescription
LoadWAV(Path): TMixChunkLoad a sound effect from file (WAV, OGG, or any supported format).
LoadWAVFromMemory(Data): TMixChunkLoad a chunk from an in-memory buffer (string of bytes).
FreeChunk(Chunk)Free a loaded chunk and release its memory.
VolumeChunk(Chunk, Vol): IntegerSet the default volume for a chunk (0–128). Applied on every PlayChannel call.
PlayChannel(Channel, Chunk, Loops): IntegerPlay chunk on channel (-1 = first free). Loops: 0 = once, -1 = infinite. Returns channel used.
FadeInChannel(Channel, Chunk, Loops, Ms): IntegerPlay with fade-in over Ms milliseconds. Returns channel used.

Music (Background)

FunctionDescription
LoadMusic(Path): TMixMusicLoad 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.
PauseMusicPause the music stream.
ResumeMusicResume a paused music stream.
HaltMusicImmediately stop the music stream.
VolumeMusic(Vol): IntegerSet music volume 0–128. Returns previous volume.
PlayingMusic: BooleanReturns True if music is currently playing (not halted).
PausedMusic: BooleanReturns True if music is paused.
FadingMusic: TMixFadingReturns mfNone, mfIn, or mfOut depending on current fade state.
MusicType(Music): TMixMusicTypeReturns the detected format type of a loaded music handle.
MusicTitle(Music): stringReturns the title metadata tag of the music file, if any.
MusicDuration(Music): DoubleReturns the duration of the music in seconds.
SetMusicPosition(Pos)Seek to position in seconds (OGG, MP3, FLAC, MOD).

Positional Audio

FunctionDescription
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

Classic chiptune formats

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
System library required:
sudo apt install libsdl2-mixer-dev

Package Info

Version1.0.0
Typeclib
C LibrarySDL2_mixer
CategoryMultimedia

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