views:

618

answers:

3

I'd like to include an MP3 with my app and play it on demand. Unfortunately I am not sure how to get started. I keep reading about .caf files, but I am not sure what those are.

I am looking for a step by step, if possible.

+1  A: 

Maybe look at: http://iphoneincubator.com/blog/audio-video/simple-way-to-play-mp3-audio-files and http://cocoawithlove.com/2008/09/streaming-and-playing-live-mp3-stream.html?

PF1
Link #1 is cheating - I don't actually need an interface, just a sound. Link #2 playing it on the Mac, not iPhone.
AngryHacker
Hi AngryHacker: Yeah, I kind of figured the first link wasn't what you were going for - but I included it in case you were in fact looking for that. As for the second link, there is a link to a "AudioStreamer" project on there, which includes the source to both the iPhone and the Mac version.
PF1
+1  A: 

Use afconvert in Terminal to convert your MP3 to a .caf. man afconvert will tell you more.

Then

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: name ofType: @"caf"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

AVAudioPlayer *player = [super initWithContentsOfURL: fileURL error: nil];
[fileURL release];
[player play];
mahboudz
Great. Where in the project do I drop the .caf file? Into the resources folder?
AngryHacker
Yes. Resources folder is good. You could have subfolders if you had multiples .cafs and wanted to keep them in their own folder.
mahboudz
One other thing to know is if you want to play the sound without any delay, you can call [player prepareToPlay] to preload it. Calling [player stop] however, may unload it, forcing -play to reload it. -pause, stops playback, and does not unload. (You could manually set the player to play from the beginning after pausing)
mahboudz