How to Play Sound Effects in Objective-C (iOS)
Mobile game or application with sound effects is usually more fun for users than without. So how to implement sound effects on iOS? There are a few ways. If you search on the net - the most frequent recommendation is to use AVAudioPlayer library and component. My opinion - don't do it if you just want to implement short sound effects that last several seconds. AVAudioPlayer is very expensive performance-wise and has lag issues. It is also not very reliable in terms of leaks since you have to release it on the audioPlayerDidFinish callback of AVAudioPlayerDelegate delegate.
AVAudioPlayer is best for playing longer loop-able music tunes as a background. In order to play short sound effects it is performance-wise cheaper to use AudioServicesPlaySystemSound method from AudioToolbox.h. In order to do that you need to declare SystemSoundID like so:
SystemSoundID audioEffect;
and don't forget to dispose it in i.e. dealloc like so:
AudioServicesDisposeSystemSoundID(audioEffect);
Below is a short example function that gets a resource file name and file extension as parameters and plays sound effect:
-(void) playSound : (NSString *) fName : (NSString *) ext { NSString *path = [[NSBundle *mainBundle] pathForResource : fName ofType :ext]; if ([[NSFileManager defaultManager] fileExistsAtPath : path]) { NSURL *pathURL = [NSURL fileURLWithPath : path]; AudioServicesCreateSystemSoundID((CFURLRef) pathURL, &audioEffect); AudioServicesPlaySystemSound(audioEffect); } else { NSLog(@"error, file not found: %@", path); } }
Enjoy :)
Thursday, May 19, 2011 1:05 PM