2009-11-09

How to play sound in an iPhone application

In the header file you must import the ‘AudioToolbox.h’ file in order to application to support for sounds. Add the following line of code in the top of the header file to import it.

#import <AudioToolbox/AudioToolbox.h>

Add the following line of codes inside the @interface in the header file.

SystemSoundID systemSoundID;

NSString *soundFilePath;

Then generate the getter and setter methods by adding the following line of code to the bottom of header file

@property (nonatomic, retain) NSString * soundFilePath;

and including the following line of code in the top of the .m file.

@synthesize soundFilePath;

Then import the sound file into your resources folder. In my example I imported an mp4 type file called ‘ruchira.mp4’.

Find the path to the sound file by adding the following code.

soundFilePath = [[NSBundle mainBundle] pathForResource:@"ruchira" ofType:@"mp4"];

Then create the system sound id for our sound file by adding the following code.

AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath: soundFilePath], & systemSoundID);

Then add the following line of code where you actually want to play that sound. For example, if you want to play the sound when a button taps, and then includes the following code in the button action method.

AudioServicesPlaySystemSound(systemSoundID);

No comments: