First Steps
To play sounds in SDL you have to get SDL_mixer.
You can download it here: http://www.libsdl.org/projects/SDL_mixer/
You want the "SDL_mixer-devel-1.2.8-VC8.zip" under Binary for Win32.
Extract it's content to your SDL folder.
And copy SDL_mixer.dll in the same folder as your .exe.
You also have to put the music file in your exe folder.
Now go to your global compiler settings.
Add "-lSDL_mixer" to the other linker options list. (without the quotation marks)
Background Sound
You have to include SDL_mixer.h in your project.
#include <SDL/SDL_mixer.h>
Now you have to prepare the music.
Mix_Music* music = NULL;
Now you have to initialize the SDL_Mixer and load the music file.
You can load the following files with Mix_LoadMUS:
- Waveform Audio (.wav)
- Ogg Vorbis (.ogg)
- Module Files (.mod)
- Mp3 Files (.mp3)
- MIDI Files (.mid, .midi)
if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1) { return 1; } music = Mix_LoadMUS("music.ogg");
This is how to actually play the music.
The music variable references to the music file we loaded.
The next argument tells how many times the music should be looped. (-1: Infinite loop, 0: None loops, 1: Loops the music once)
The if statement check if the music have problems playing. If it returns true, the program will return.
if (Mix_PlayMusic(music, -1) == -1) { return 2; }
And before quitting, you should free the music and quit SDL_Mixer.
Mix_FreeMusic(music); Mix_CloseAudio();
Sound Effects
We will load and play sound effects with a different method than the background music.
That's because if you play sound effect with the above method, the background will stop.
We want to play the sound effects while the background music is still playing.
You have to include SDL_mixer.h in your project.
#include <SDL/SDL_mixer.h>
Now you have to prepare the sound effect.
Mix_Chunk* effect = NULL;
Now you have to initialize the SDL_Mixer and load the music file.
Sound effects should always be in the wave format, so we'll use Mic_LoadWAV for this.
if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1) { return 1; } effect = Mix_LoadWAV("sound_effect.wav");
This is how to actually play the music.
The first argument is the channel to play on, use -1 to let it find a free channel for you.
The effect variable references to the sound file we loaded.
The next argument tells how many times the music should be looped. (-1: Infinite loop, 0: None loops, 1: Loops the sound once)
Normally you don't want to loop the sound effect.
The if statement check if the sound have problems playing. If it returns true, the program will return.
if(Mix_PlayChannel(-1, effect, 0) == -1) { return 2; }
And before quitting, you should free the sound and quit SDL_Mixer.
Mix_FreeChunk(effect); Mix_CloseAudio();
| Categories: SDL Tutorials : Tutorials |