Wednesday, February 18, 2009

Adding Background Music to an Application

I was stuck until very recently working on a game for the iPhone because I wasn't sure how to setup a loop of music that would act in the background.

It's quite simple to do and I based it myself off of what Chris Roper, from [URL="http://iphonedevtips.blogspot.com/2009/01/avfoundation-and-audio.html"]iPhoneDevTips[/URL], does in his article but it is slightly modified to work in the App Delegate's "applicationDidFinishLaunching."

- (void)applicationDidFinishLaunching:(UIApplication *)application /* this is where you can place code for beginning as soon as the application launches, as indicated by the section name */
{

// Override point for customization after app launch
[window addSubview:viewController.view]; /* adding my main view to the view controller */
[window makeKeyAndVisible]; //


AVAudioPlayer *myExampleSound; /* this variable can be named differently - This line is subclassing AVAudioPlayer */

NSString *myExamplePath = [[NSBundle mainBundle] pathForResource:@"*Music filename*" ofType:@"mp3"]; /* *Music filename* is the name of the file that you want to play. BE SURE that you type the correct characters as the system is case-sensitive. It caused a crash for me... Very painful. */

myExampleSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:myExamplePath] error:nil]; // this is setting a path so that the content can be loaded.

myExampleSound.delegate = self;

[myExampleSound play];
//[myExampleSound stop];

[myExampleSound prepareToPlay];

myExampleSound.numberOfLoops = 10; /* can be as many times as needed by the application */

}


You can insert this in quite a few general places. MAKE SURE to #import the AudioToolBox framework and AVFoundation framework into your main header file in order to not have problems during the build/compile process.

---------------------------------------------------------------------------------------------------------------

Leave comments below if you see any issues with the code or have questions about it.

No comments:

Post a Comment