iOS 系統聲音播放

來源:互聯網
上載者:User

標籤:

    在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 系統聲音播放

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.