A simple SDL2 audio library without SDL_Mixer for playing music and multiple sounds natively in SDL2
src/audio.c
and src/audio.h
in your projectsrc/test.c
shows all the functionality possible:Basic use case:
// Initialize SDL2 Audio only
SDL_Init(SDL_INIT_AUDIO);
// Initialize Simple-SDL2-Audio
initAudio();
// Play music and a sound
playMusic("music/highlands.wav", SDL_MIX_MAXVOLUME);
playSound("sounds/door1.wav", SDL_MIX_MAXVOLUME / 2);
// Let play for 1 second
SDL_Delay(1000);
// End Simple-SDL2-Audio
endAudio();
// End SDL2
SDL_Quit();
// Initialize Simple-SDL2-Audio on default audio device
void initAudio(void);
// Play many Sounds or single Musics
void playSound(const char * filename, int volume);
void playMusic(const char * filename, int volume);
// Clean up Simple-SDL2-Audio
void endAudio(void);
// Pause or Unpause running audio
void pauseAudio(void);
void unpauseAudio(void);
// Advanced functions used for caching WAV files in memory, create, play many times, free
Audio * createAudio(const char * filename, uint8_t loop, int volume);
void playSoundFromMemory(Audio * audio, int volume);
void playMusicFromMemory(Audio * audio, int volume);
void freeAudio(Audio * audio);
Only one music can play at a time, and it loops (to close music you can just run endAudio()
, or use pauseAudio()
and unpauseAudio()
).
Any number of sounds can be played at once, but obviously the more, can become distorted
AUDIO_MAX_SOUNDS
in src/audio.c
to limit how many sounds can be played at once to reduce distortion from too many playingSDL_AUDIO_ALLOW_CHANGES
in src/audio.c
, see the top of src/audio.c
to set the format, stereo vs mono etc... No conversionplayMusic()
functions makes a disk read each call. To only make one disk read, cache, and play the audio from memory, use the createAudio(); playSoundFromMemory(); freeAudio();
functions (recommend storing the Audio* object in a dictionary / hashmap)SDL_QueueAudio()
(no callback)SDL2.0.6 updated how audio was handled, for Windows 7 using a later release of SDL2, you need to set #define SDL_AUDIO_ALLOW_CHANGES SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_CHANNELS_CHANGE
which is a flag near the top of the file.