Advertisement

SDL Mixer

Started by June 30, 2015 07:58 PM
2 comments, last by fastcall22 9 years, 6 months ago

hi all, I have created a text adventure game in C, and I am trying to add music to play in the background during it.

I am trying to use SDL_Mixer to accomplish this but whenever I play the music .wav file, the game pauses until it is finished. Is there a way I can let them play the console game and just have the music repeat in the background? At the moment I just have a function called "s" that I copied the below code into from a tutorial :


void s(void)
{
    Mix_Chunk *sound = NULL;		//Pointer to our sound, in memory
	int channel;				//Channel on which our sound is played

	int audio_rate = 22050;			//Frequency of audio playback
	Uint16 audio_format = AUDIO_S16SYS; 	//Format of the audio we're playing
	int audio_channels = 2;			//2 channels = stereo
	int audio_buffers = 4096;		//Size of the audio buffers in memory

	//Initialize BOTH SDL video and SDL audio
	if (SDL_Init(SDL_INIT_AUDIO) != 0) {
		printf("Unable to initialize SDL: %s\n", SDL_GetError());
		return 1;
	}

	//Initialize SDL_mixer with our chosen audio settings
	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) != 0) {
		printf("Unable to initialize audio: %s\n", Mix_GetError());
		exit(1);
	}

	//Load our WAV file from disk
	sound = Mix_LoadWAV("music.wav");
	if(sound == NULL) {
		printf("Unable to load WAV file: %s\n", Mix_GetError());
	}

	//Set the video mode to anything, just need a window


	//Play our sound file, and capture the channel on which it is played
	channel = Mix_PlayChannel(-1, sound, 0);
	if(channel == -1) {
		printf("Unable to play WAV file: %s\n", Mix_GetError());
	}

	//Wait until the sound has stopped playing
	while(Mix_Playing(channel) != 0);
	//Release the memory allocated to our sound
	Mix_FreeChunk(sound);

	//Need to make sure that SDL_mixer and SDL have a chance to clean up
	Mix_CloseAudio();
	SDL_Quit();
}

thanks!

//Wait until the sound has stopped playing
while(Mix_Playing(channel) != 0);

Advertisement

Ah sorry, I tried commenting that out before, but forgot to put the SDL Exit code elsewhere.

Thanks

I forgot to put the SDL Exit code elsewhere.


Well, there's more to it than that. You should part out the initialization, loading, cleanup, and shutdown in s to their respective parts in your program, such that s is responsible for just starting the music.

just have the music repeat in the background?

Mix_PlayChannel's 3rd parameter can be set to -1 to set infinite looping.

This topic is closed to new replies.

Advertisement