Playing Audio with SDL2
The lesson focused on graphics and input. How can I play audio in my SDL2 application?
To play audio with SDL2, you can use the SDL_mixer extension library, which provides a simple API for loading and playing audio files.
First, make sure you have SDL_mixer installed and added to your project (similar to how SDL_image and SDL_ttf were added in the lesson).
Here's a simple example of loading and playing an audio file with SDL_mixer:
#include <SDL.h>
#include <SDL_mixer.h>
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_AUDIO);
Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT,
2, 2048);
Mix_Music* music{Mix_LoadMUS("music.mp3")};
if (!music) {
// Error handling
return 1;
}
Mix_PlayMusic(music, -1);
// Main loop
// ...
bool quit = false;
while (!quit) {
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
quit = true;
}
}
}
Mix_FreeMusic(music);
Mix_CloseAudio();
SDL_Quit();
return 0;
}
This code:
- Initializes the SDL audio subsystem with
SDL_Init(SDL_INIT_AUDIO)
- Opens the audio device with
Mix_OpenAudio
- Loads an audio file with
Mix_LoadMUS
- Plays the loaded audio with
Mix_PlayMusic
(-1 means loop indefinitely) - Frees the audio resources when done
SDL_mixer supports various audio formats like MP3, WAV, OGG, and MOD. You can also load and play short sound effects using Mix_LoadWAV
and Mix_PlayChannel
.
Remember to link against the SDL_mixer library when compiling:
g++ ... -lSDL2 -lSDL2_mixer ...
Building SDL2 from a Subdirectory (CMake)
A step-by-step guide on setting up SDL2 and useful extensions in a project that uses CMake as its build system