SDL_mixer
is an add‑on library for SDL2 that simplifies loading and playing sound effects and music in multiple formats (WAV, OGG, MP3, FLAC, MOD, etc.). It wraps lower‑level SDL_Audio
APIs with a higher‑level mixer, channels, and music interface.
Link with -lSDL2_mixer
and include <SDL_mixer.h>
.
macOS (Homebrew)
brew install sdl2_mixer
Ubuntu / Debian
sudo apt-get install libsdl2-mixer-dev
Ensure matching SDL2 and SDL_mixer versions.
SDL_Init(SDL_INIT_AUDIO);
int flags = MIX_INIT_MP3 | MIX_INIT_OGG | MIX_INIT_FLAC;
int initted = Mix_Init(flags);
if ((initted & flags) != flags) {
fprintf(stderr, "Mix_Init: failed to load some codecs → %s\n", Mix_GetError());
}
int freq = 48000; /* Output sample rate */
Uint16 format = MIX_DEFAULT_FORMAT; /* AUDIO_S16LSB */
int channels = 2; /* Stereo */
int chunks = 1024; /* Internal chunk size */
if (Mix_OpenAudio(freq, format, channels, chunks) < 0) {
fprintf(stderr, "Mix_OpenAudio: %s\n", Mix_GetError());
}
Mix_Init
flags
– bitmask of codecs to enable (MIX_INIT_*
).&
).Mix_OpenAudio
freq
– desired output sample rate (Hz).format
– AUDIO_S16SYS
, AUDIO_F32SYS
, etc. Use MIX_DEFAULT_FORMAT
(signed 16‑bit).channels
– 1 = mono, 2 = stereo.chunksize
– mixer buffer size in samples. Power of two recommended; affects latency.
Mix_Chunk* pew = Mix_LoadWAV("laser.wav");
Mix_Music* bgm = Mix_LoadMUS("theme.ogg");
Mix_LoadWAV
/Mix_LoadMUS
file
– path to audio file (WAV recommended for FX; OGG/MP3 for music).Mix_Chunk
/ Mix_Music
or NULL
on error.
int channel = Mix_PlayChannel(-1, pew, 0);
Mix_PlayMusic(bgm, -1); /* loop indefinitely */
Mix_PlayChannel
channel
– -1
= first free channel or index 0‑7 etc.chunk
– pointer to Mix_Chunk
.loops
– 0
= play once; n
= loop n extra times; -1
= forever.Mix_PlayMusic
music
– pointer to Mix_Music
.loops
– -1
infinite; 0
once; n
loops n extra.
Mix_Volume(channel, 64); /* 0‑128 for this channel */
Mix_VolumeChunk(pew, 90); /* affects all future plays */
Mix_VolumeMusic(32); /* music volume */
Mix_Pause(channel);
Mix_Resume(channel);
Mix_HaltChannel(channel);
Mix_PauseMusic();
Mix_ResumeMusic();
Mix_FadeOutMusic(2000); /* ms fade‑out */
0
silent → 128
max.Mix_FadeOutMusic
– milliseconds to fade.
if (Mix_Playing(channel)) {
/* still playing */
}
if (!Mix_PlayingMusic()) {
/* music finished */
}
Use Mix_Paused
/Mix_PausedMusic
similarly.
Mix_FreeChunk(pew);
Mix_FreeMusic(bgm);
Mix_CloseAudio();
Mix_Quit();
Call after all audio usage to release resources.
fprintf(stderr, "SDL_mixer error: %s\n", Mix_GetError());
Always check return values & print Mix_GetError()
on failure.