SDL mixer:Tutorials:Playing an OGG Music File

From GDWiki

Jump to: navigation, search

Howdy folks! This tutorial will build on what we've already learned in the Playing a WAV Sound File tutorial, so be sure you've read it! SDL_mixer can be used for more than just sound effects; Music files such as MP3s and Oggs can also be played, with nifty fading effects, end-of-song callbacks, and more. For the purposes of this tutorial, we'll be using an Ogg file because the lovely people at Xiph were kind enough to develop Ogg as an open standard; no licenses required!

Play that funky music, white boy!

Alright, lets get to it. First of all, we need to initialize SDL video and SDL audio. This can be done identically to the method used in the Playing a WAV Sound File tutorial, so we won't rehash the code analysis here. Instead, we'll move on to the music-specific code:

Mix_Music *music;
music = Mix_LoadMUS("music.ogg");
if(music == NULL) 
{
	printf("Unable to load Ogg file: %s\n", Mix_GetError());
	return 1;
}

The above code will attempt to use the Mix_LoadMUS function to load a file called music.ogg from disk. On success, a valid Mix_Music pointer will be returned.

Next, we'll play the music file we just loaded:

if(Mix_PlayMusic(music, 0) == -1) 
{
	printf("Unable to play Ogg file: %s\n", Mix_GetError());
	return 1;
}

The Mix_PlayMusic call accepts two parameters. First, a pointer to a Mix_Music struct, and second, an int representing the number of times we'd like the music sequence to be looped. If you'd like infinite looping, pass a value of -1 as your loop parameter. For the purposes of this tutorial, we want to play the Ogg file only once, so we'll pass 0.

musicPlaying = 1;
Mix_HookMusicFinished(musicFinished);
 
while(musicPlaying)
{
	//Do nothing for a bit
	SDL_Delay(100);
}

The code above uses a while loop to delay until the music has finished playing. The Mix_HookMusicFinished function accepts a pointer to a void function as its only parameter; the pointed function will be called when the music loops have completed playback:

void musicFinished()
{
	musicPlaying = 0;
}

The above function will be executed when the music stops, setting the musicPlaying global int to zero. This will cause the while loop in our previous code segment to cease execution! The program will then continue with a bit of final cleanup:

Mix_HaltMusic();
Mix_FreeMusic(music);
Mix_CloseAudio();

Just to be on the safe side, Mix_HaltMusic is called. Then, we must release the memory pointed to by our Mix_Music pointer by calling Mix_FreeMusic. Finally, Mix_CloseAudio is called, ending the SDL_mixer session.

[edit] Source code

  • The source code for this tutorial can be found by clicking here.
Categories