標籤:
在iOS中可通過兩種方式去播放聲音:
* 播放壓縮的音效檔,比如mp3檔案,一般使用播放聲音中提到的方法,適用於播放時間較長,比如大於30秒,AVAudioPlayer可以提供更多的控制特性,比如暫停等等
* 播放系統聲音,比如翻頁的嘩啦聲,應該使用播放系統聲音的方法,因為壓縮的音效檔比播放wav等非壓縮音效檔在播放前消耗更多的處理器資源,這樣的聲音還要頻繁的播放,而且,因為系統音效檔都較小,一般小於30秒,因此即使壓縮格式,也不會節省多少儲存空間。
播放系統聲音:首先要匯入系統架構 <AudioToolbox/AudioToolbox.h>
播放系統聲音,基本思路是:
* 在播放前,比如控制器初始化階段,註冊系統聲音,並儲存一個系統聲音id
* 在需要播放系統聲音的時候只需調用系統服務的全域方法,傳入系統聲音id即可
在我們瞭解了基本思路後,就可以上代碼了:
*.h檔案
+ (void)initSystemSoundWithName:(NSString *)soundName SoundType:(NSString *)soundType{ [ZKAudioToolBox initAudioToolBox]; if (audioTool) { //得到音頻路徑 NSString *path=[NSString stringWithFormat:@"/System/Library/Audio/UISounds/%@.%@",soundName,soundType]; if (path) { OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&audioTool->sound); if (error != kAudioServicesNoError) {//擷取的聲音的時候,出現錯誤 audioTool->sound=nil; } //擷取自訂的聲音// NSString *thesoundFilePath = [[NSBundle mainBundle] pathForResource:soundName ofType:soundType]; //音樂檔案路徑// CFURLRef thesoundURL = (__bridge CFURLRef)[NSURL fileURLWithPath:thesoundFilePath];// AudioServicesCreateSystemSoundID(thesoundURL, &audioTool->sound); //開始播放聲音 AudioServicesPlaySystemSound(audioTool->sound); } }}
如上就能正常的播放聲音了,寫成單例的形式,就能便於多個頁面調用!!!
iOS 系統聲音播放