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:
SDL_Init(SDL_INIT_AUDIO)
Mix_OpenAudio
Mix_LoadMUS
Mix_PlayMusic
 (-1 means loop indefinitely)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 ...
Answers to questions are automatically generated and may not have been reviewed.
A step-by-step guide on setting up SDL2 and useful extensions in a project that uses CMake as its build system