Building SDL2 from a Subdirectory (CMake)

Playing Audio with SDL2

The lesson focused on graphics and input. How can I play audio in my SDL2 application?

Vector illustration representing computer programming

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 ...

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 27 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved