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:

  1. Initializes the SDL audio subsystem with SDL_Init(SDL_INIT_AUDIO)
  2. Opens the audio device with Mix_OpenAudio
  3. Loads an audio file with Mix_LoadMUS
  4. Plays the loaded audio with Mix_PlayMusic (-1 means loop indefinitely)
  5. 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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Troubleshooting CMake Errors with SDL2
I followed the lesson but I am getting CMake errors when trying to build my project with SDL2. How can I troubleshoot this?
Using SDL2 without CMake
Is it possible to use SDL2 in my C++ project without using CMake? How would I set that up?
Enabling VSync with SDL2
How can I enable vertical synchronization (VSync) in my SDL2 application to prevent screen tearing?
Creating a Fullscreen Window with SDL2
How do I create a fullscreen window using SDL2 instead of a windowed one?
Implementing a Basic Game Loop with SDL2
The lesson's example code uses a simple while loop for the main game loop. What does a more complete game loop look like in SDL2?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant