iOS開發:發出系統的聲音!發出自己的聲音!
這個連結非常詳盡地列舉了IOS7裡面所有的系統聲音,聲音的ID,聲音的存放位置 儘管現在已經是ios8的時代,但是系統聲音這個東東不會因此過時,畢竟聲音就那幾十種,不會一下子有太大變化。 https://github.com/TUNER88/iOSSystemSoundsLibrary
這個stackoverflow裡面有一些比較有用的資訊和連結,包括怎樣播放系統聲音,怎樣查看ref http://stackoverflow.com/questions/7831671/playing-system-sound-without-importing-your-own
還有一個很兇殘的github項目,他把所有.framework都放上去,供大家下載。其中有我剛好需要的audiotoolbox https://github.com/EthanArbuckle/IOS-7-Headers
這個部落格教怎麼使用系統封裝好的API http://www.cnblogs.com/martin1009/archive/2012/06/14/2549473.html
假如要做一個模組,要求能夠在系統需要的地方播放短暫的音效,那麼就可以寫以下這麼一個類,用上單例模式,讓其全域可用。 關於單例,我也寫過一篇簡單的介紹,在此不做介紹。當然,不使用單例模式也是完全沒問題的。
// CHAudioPlayer.h// Created by HuangCharlie on 3/26/15.#import #import #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 CHAudioPlayerIMPL_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
這裡有一個地方十分要注意! 如果要使用自己的資源來播放的話,會使用到updateWithResource. 其中,下面的那兩行代碼如果寫成分開的,就沒有什麼問題。如果寫到一起,很可能會因為非同步原因或者其他原因造成crash。故要分開寫如下。
//註冊聲音到系統 NSURL* url = [NSURL fileURLWithPath:path];CFURLRef inFileURL = (__bridge CFURLRef)url;