Friday, May 8, 2009

Playing sound with AVAudioPlayer

First of all, you need to append "AVFoundation.framework" to your frameworks list.
Groups & Files -> Frameworks -> Add -> Existing Frameworks -> /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.1.sdk/System/Library/Frameworks/AVFoundation.framework


Import avfoundation.h.


#import <avfoundation/avfoundation.h>


Code like this.



NSString *path = [[NSBundle mainBundle] pathForResource:@"MySong" ofType:@"caf"];
AVAudioPlayer* player =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self; //for releasing object.
[player play];


To manage memory, you should build delegate method on your controller.

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
[player release];
}


To convert .mp3 to .caf or another, use "afconvert" like below.

/usr/bin/afconvert -f caff -d ima4 sound.mp3 sound.caf

No comments:

Post a Comment