Saturday, February 5, 2011

Playing sound with iPhone SDK

Today I learned to play sound with iPhone SDK, this is first time I worked with sound instead of graphics. So posted my experience here.

In case you need to play short sound in your iPhone App for application action like button click or something similar you can try following code sample.

First of all you need to add Audio Toolbox framework to your project. You can add it like shown in below snap. Right click on Frameworks -> Add -> Existing Frameworks...



After adding audio framework, you can use AudioServices API to play sound. You will need to import AudioToolbox/AudioServices.h file to your header file.

#import <AudioToolbox/AudioServices.h>

Then we need to create system sound id using audio service API like shown in below code.

SystemSoundID soundId;
NSString* soundPath = [[NSBundle mainBundle] pathForResource:@"Sound4" ofType:@"wav"];
CFURLRef soundUrl = (CFURLRef) [NSURL fileURLWithPath:soundPath];
AudioServicesCreateSystemSoundID(soundUrl, &soundId);

After creating system sound id, we can use that id to play sound using following code,

AudioServicesPlaySystemSound(soundId);

Now code part is done, you still need to add actual sound file to resources. After adding sound file to resource you can run your application to play sound.

No comments:

Post a Comment