这段代码能十分简单地播放简短的音效。在需要播放简单的声音文件,并且不需要重复播放时,可以使用这种方法。
#import <AudioToolbox/AudioServices.h>
-(void) playSound : (NSString *) fName : (NSString *) ext
{
NSString *path = [[NSBundle *mainBundle] pathForResource : fName ofType :ext];
if ([[NSFileManager defaultManager] fileExistsAtPath : path])
{
NSURL *pathURL = [NSURL fileURLWithPath : path];
SystemSoundID audioEffect;
AudioServicesCreateSystemSoundID((CFURLRef) pathURL, &audioEffect;);
AudioServicesPlaySystemSound(audioEffect);
}
else
{
NSLog(@"error, file not found: %@", path);
}
//在非ARC模式下,还需要释放 audioEffect
AudioServicesDisposeSystemSoundID(audioEffect);
}