在你讀這篇文章之前,如果你不嫌讀英文太累,推薦閱讀下蘋果iOS Human Interface Guidelines中Sound這一章。
選擇一個Category
AVAudioSessionCategoryAmbient
或 kAudioSessionCategory_AmbientSound
——用於非以語音爲主的應用,使用這個category的應用會隨着靜音鍵和屏幕關閉而靜音。並且不會中止其它應用播放聲音,可以和其它自帶應用如iPod,safari等同時播放聲音。注意:該Category無法在後臺播放聲音
AVAudioSessionCategorySoloAmbient
或 kAudioSessionCategory_SoloAmbientSound
——類似於AVAudioSessionCategoryAmbient 不同之處在於它會中止其它應用播放聲音。 這個category爲默認category。該Category無法在後臺播放聲音
AVAudioSessionCategoryPlayback
或 kAudioSessionCategory_MediaPlayback
——用於以語音爲主的應用,使用這個category的應用不會隨着靜音鍵和屏幕關閉而靜音。可在後臺播放聲音
AVAudioSessionCategoryRecord
或 kAudioSessionCategory_RecordAudio
———
用於需要錄音的應用,設置該category後,除了來電鈴聲,鬧鐘或日曆提醒之外的其它系統聲音都不會被播放。該Category只提供單純錄音功能。
AVAudioSessionCategoryPlayAndRecord
或 kAudioSessionCategory_PlayAndRecord
——用於既需要播放聲音又需要錄音的應用,語音聊天應用(如微信)應該使用這個category。該Category提供錄音和播放功能。如果你的應用需要用到iPhone上的聽筒,該category是你唯一的選擇,在該Category下聲音的默認出口爲聽筒(在沒有外接設備的情況下)。
注意:並不是一個應用只能使用一個category,程序應該根據實際需要來切換設置不同的category,舉個例子,錄音的時候,需要設置爲AVAudioSessionCategoryRecord,當錄音結束時,應根據程序需要更改category爲AVAudioSessionCategoryAmbient,AVAudioSessionCategorySoloAmbient或AVAudioSessionCategoryPlayback中的一種。
設置Category
- NSError *setCategoryError = nil;
- BOOL success = [[AVAudioSession sharedInstance]
- setCategory: AVAudioSessionCategoryAmbient
- error: &setCategoryError];
- if (!success) { /* handle the error in setCategoryError */ }
Activate & Deactivate AudioSession
- NSError *error = nil;
- AVAudioSession *audioSession = [AVAudioSession sharedInstance];
- BOOL ret = [audioSession setActive:YES error:&error];
- if (!ret)
- {
- NSLog(@"%s - activate audio session failed with error %@", __func__,[error description]);
- }
- NSError *error = nil;
- AVAudioSession *audioSession = [AVAudioSession sharedInstance];
- //Note: Set AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation to resume other apps' audio.
- BOOL ret = [audioSession setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];
- if (!ret)
- {
- }
Audio Route的選擇
當你的iPhone接有多個外接音頻設備時(耳塞,藍牙耳機等),AudioSession將遵循last-in wins的原則來選擇外接設備,即聲音將被導向最後接入的設備。
當沒有接入任何音頻設備時,一般情況下聲音會默認從揚聲器出來,但有一個例外的情況:在PlayAndRecord
這個category下,聽筒會成爲默認的輸出設備。如果你想要改變這個行爲,可以提供MPVolumeView來讓用戶切換到揚聲器,也可通過overrideOutputAudioPort方法來programmingly切換到揚聲器,也可以修改category
option爲AVAudioSessionCategoryOptionDefaultToSpeaker。
PlayandRecord下切換到揚聲器
除了讓用戶手動選擇,你也可以通過以下兩種方法在程序裏進行切換
1. 修改Category的默認行爲:
- [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:&error];
- [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];