Tuesday, December 15, 2009

Sound Playback in iPhone

Today I am going to post two ways to play sounds in iPhone.

1st Approach: Using Audio Toolbox
NSString *sound = [NSString stringWithFormat:@"sound"];
NSString *path = [[NSBundle mainBundle] pathForResource:sound ofType:@"wav"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);
AudioServicesPlaySystemSound(soundID);


Of course, for this to work you need to add the AudioToolbox foundation to your project. Also it doesn't like the compressed audio of mp3's, etc. It is more suited for wav's.

2nd Approach: Using AVAudioPlayer class
The AVAudioPlayer class makes it very easy to play mp3s as well.
-(IBAction)playSound:(id)sender{

NSString *newAudioFile = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"mp3"];

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:newAudioFile] error:NULL];

[audioPlayer setDelegate:self];
[audioPlayer prepareToPlay];
BOOL plays = [audioPlayer play];

}


For this to work, you need to add the AVFoundation to your project:
Project -> Add ->
Developer:Platforms:iPhoneSimulator.platform:Developer:SDKs:iPhoneSiumulator2.2.sdk:System:Library:Frameworks:AVFoundation.framework

Make sure to NOT copy it into your project when you are given the dialog box.

AVAudioPlayer provides a really straightforward interface, but it might not be appropriate for playing really short sounds that are synchronized with your app. AudioServices is really intended to play short sounds, and it works very well for that.

Adding the following line to your code, before you start the player, should cause the audioPlayer to loop indefinitely, until you issue a stop message:
[audioPlayer setNumberOfLoops:-1];

after the setDelegate function call.

Note that, with MP3, you may run into issues if you need to play multiple sounds at the same time:

Coding How-Tos: Audio and Video
The following limitations pertain for simultaneous sounds in iPhone OS, depending on the audio data format:

* AAC, MP3, and ALAC (Apple Lossless) audio: no simultaneous playback; one sound at a time.