Although its been a while since I figured out how to play an audio file in an iPhone app, it still is a pain in the ass every time I try to make it work on a new app. I still keep doing some trial and errors or refer to the numerous blogs out there helping out fellow iPhone app developers. So I decided to once and for all document the steps that I usually take to play a sound file. Typically the file extensions that are allowed are:
- .caf
- .m4a
- .wav
- .mp3
In my opinion I find the first 3 easier to work with rather than the popular .mp3 format. For some reason there are audio clips in .mp3 format which don’t seem to work. Luckily there are so many .mp3 to .wav converters around which you can use. Or the easiest way will be to use iTunes to convert to AAC format which will assign a .m4a extension for the audio clip. Anyway, here are the steps you need to follow to play an audio file in your iPhone app.
1. Copy the audio file to your project directory
2. Create a file called SoundEffects.h with the following code:
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioServices.h>
@interface SoundEffect : NSObject {
SystemSoundID soundID;
}
- (id) initWithContentsOfFile:(NSString *)path;
-(void)play;
@end
3. Create another file called SoundEffects.m and add the following code to it:
#import “SoundEffect.h”
@implementation SoundEffect
- (id) initWithContentsOfFile:(NSString *)path;
{
self = [super init];
if (self != nil) {
NSURL *filePath = [NSURL fileURLWithPath: path isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
}
return self;
}
-(void)play {
AudioServicesPlaySystemSound(soundID);
}
@end
4. Add the following code in your main.m
-(void) awakeFromNib {
NSBundle *mainBundle = [NSBundle mainBundle];
soundEffect = [[SoundEffect alloc] initWithContentsOfFile:[mainBundle pathForResource:@"farSound" ofType:@"caf"]];
}
5. At the place where you want to play the sound file, add the following code:
[soundEffect play];
You will need to manually add the Audio Toolkit framework to your application bundle as well. This is a step that a lot of developers forget to do. If you do not do this, then your project will not compile. Wish Apple could make this much more straightforward rather than going through so many steps and invoking the Audio Toolkit framework. Anyway, hope this will be helpful for your development and as usual do let me know if you face any problems.
If you enjoyed this post, make sure you subscribe to my RSS feed!



#1 by Tanay Kumar Das - November 20th, 2009 at 01:23
This is awesome, exactly what I trying to learn. However I’m so new at this. I tried reading the other articles in hopes to figure out how to start, but getting confused. Can you help and post a video demonstration for this whole affair. I would really appreciate it.
Tanay Kumar Das´s last blog ..My Phone Riches Review-Is it A Scam?