// CHAudioPlayer.h // Created by HuangCharlie on 3/26/15. #import <Foundation/Foundation.h> #import <AudioToolbox/AudioToolbox.h> #import "SynthesizeSingleton.h" @interface CHAudioPlayer : NSObject { } DEF_SINGLETON_FOR_CLASS(CHAudioPlayer); // play system vibration of device -(void)updateWithVibration; //play system sound with id, more detail in system sound list // system sound list at: // https://github.com/TUNER88/iOSSystemSoundsLibrary // check for certain sound if needed -(void)updateWithSoundID:(SystemSoundID)soundId; // play resource sound, need to import resource into project -(void)updateWithResource:(NSString*)resourceName ofType:(NSString*)type; // action of play -(void)play; @end // CHAudioPlayer.m // Created by HuangCharlie on 3/26/15. #import "CHAudioPlayer.h" @interface CHAudioPlayer() @property (nonatomic,assign) SystemSoundID soundID; @end @implementation CHAudioPlayer IMPL_SINGLETON_FOR_CLASS(CHAudioPlayer); //vibration -(void)updateWithVibration { self.soundID = kSystemSoundID_Vibrate; } -(void)updateWithSoundID:(SystemSoundID)soundId { self.soundID = soundId; } //sound of imported resouces, like wav -(void)updateWithResource:(NSString*)resourceName ofType:(NSString*)type { [self dispose]; NSString *path = [[NSBundle mainBundle] pathForResource:resourceName ofType:type]; if (path) { //注册声音到系统 NSURL* url = [NSURL fileURLWithPath:path]; CFURLRef inFileURL = (__bridge CFURLRef)url; SystemSoundID tempSoundId; OSStatus error = AudioServicesCreateSystemSoundID(inFileURL, &tempSoundId); if(error == kAudioServicesNoError) self.soundID = tempSoundId; } } -(void)play { AudioServicesPlaySystemSound(self.soundID); } -(void)dispose { AudioServicesDisposeSystemSoundID(self.soundID); } @end
//注册声音到系统 NSURL* url = [NSURL fileURLWithPath:path]; CFURLRef inFileURL = (__bridge CFURLRef)url;
原文地址:http://blog.csdn.net/hyichao_csdn/article/details/45293321