Game Development Community

dev|Pro Game Development Curriculum

Pausing Background Music on iPhone

by Dave Calabrese · 07/31/2009 (1:39 pm) · 1 comments

For anyone who wants to be able to pause and unpause their background music in the iPhone app... this resource is for you! Thanks to the strong iPhone SDK, the functionality to handle this already exists. It just hasn't been wired in to iTorque2D yet. Wiring it in however is actually very easy!

Here are the engine code changes needed to make this happen:

iPhoneStreamSource.cc, around line 46
void iPhoneStreamSource::pause() {
	SoundEngine::SoundEngine_PauseBackgroundMusic();
}

void iPhoneStreamSource::unpause() {
	SoundEngine::SoundEngine_UnpauseBackgroundMusic();
}


soundEngine.mm, around line 866
OSStatus Pause()
		{
			return AudioQueuePause(mQueue);
		}
		
		OSStatus Unpause()
		{
			return AudioQueueStart(mQueue,false);
		}

soundEngine.mm, around line 1563
extern "C"
OSStatus  SoundEngine_PauseBackgroundMusic()
{
	return (sBackgroundTrackMgr) ?  sBackgroundTrackMgr->Pause() : kSoundEngineErrUnitialized;
}
	
extern "C"
OSStatus  SoundEngine_UnpauseBackgroundMusic()
{
	return (sBackgroundTrackMgr) ?  sBackgroundTrackMgr->Unpause() : kSoundEngineErrUnitialized;
}

audioFunctions.cc, around line 654
ConsoleFunction(pauseiPhoneAudioStream, S32, 2, 3, "pauseiPhoneAudioStream(Stream ID)" )
{
	int objID = dAtoi( argv[1] );
	SimObject *sObj = Sim::findObject( objID );
	iPhoneStreamSource *stream = (iPhoneStreamSource*)(sObj);
	if( stream ) 
	{
		if( stream->isPlaying() ) 
		{
			stream->pause();
		}
		else
			Con::errorf("Stream is not playing!");
	}
	else
		Con::errorf("Stream does not exist!");
}

ConsoleFunction(unpauseiPhoneAudioStream, S32, 2, 3, "unpauseiPhoneAudioStream(Stream ID)" )
{
	int objID = dAtoi( argv[1] );
	SimObject *sObj = Sim::findObject( objID );
	iPhoneStreamSource *stream = (iPhoneStreamSource*)(sObj);
	if( stream ) 
	{
		stream->unpause();
	}
	else
		Con::errorf("Stream does not exist!");
}


Then all you need to do is call the following from script when you want to pause and unpause:
pauseiPhoneAudioStream($activeAudioStrem);
unpauseiPhoneAudioStream($activeAudioStrem);

Enjoy!