iOS AudioSession详解 Category选择 听筒扬声器切换

在你读这篇文章之前,如果你不嫌读英文太累,推荐阅读下苹果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

 
  1. NSError *setCategoryError = nil;  
  2. BOOL success = [[AVAudioSession sharedInstance]  
  3.                 setCategory: AVAudioSessionCategoryAmbient  
  4.                 error: &setCategoryError];  
  5.   
  6. if (!success) { /* handle the error in setCategoryError */ }  

Activate & Deactivate AudioSession

 
  1. NSError *error = nil;  
  2. AVAudioSession *audioSession = [AVAudioSession sharedInstance];  
  3. BOOL ret = [audioSession setActive:YES error:&error];  
  4. if (!ret)  
  5. {  
  6.     NSLog(@"%s - activate audio session failed with error %@", __func__,[error description]);  
  7. }  
  1. NSError *error = nil;  
  2. AVAudioSession *audioSession = [AVAudioSession sharedInstance];  
  3. //Note: Set AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation to resume other apps' audio.  
  4. BOOL ret = [audioSession setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];  
  5. if (!ret)  
  6. {  
  7. }  



Audio Route的选择

当你的iPhone接有多个外接音频设备时(耳塞,蓝牙耳机等),AudioSession将遵循last-in wins的原则来选择外接设备,即声音将被导向最后接入的设备。

当没有接入任何音频设备时,一般情况下声音会默认从扬声器出来,但有一个例外的情况:在PlayAndRecord这个category下,听筒会成为默认的输出设备。如果你想要改变这个行为,可以提供MPVolumeView来让用户切换到扬声器,也可通过overrideOutputAudioPort方法来programmingly切换到扬声器,也可以修改category option为AVAudioSessionCategoryOptionDefaultToSpeaker。


PlayandRecord下切换到扬声器

除了让用户手动选择,你也可以通过以下两种方法在程序里进行切换

1. 修改Category的默认行为:

  1. [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:&error];  

2. OverrideOutputAudioPort:

 
  1. [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];  
原文地址:https://www.cnblogs.com/Milo-CTO/p/4365199.html