AVAudioSession - Category、Model、Options、Error参数详解

[AVAudioSession sharedInstance] 五种设置方法

         [[AVAudioSession sharedInstance] setCategory:<#(nonnull NSString *)#>4
                                                error:<#(NSError * _Nullable __autoreleasing * _Nullable)#>];

        [[AVAudioSession sharedInstance] setMode:<#(nonnull NSString *)#>
                                                    error:<#(NSError * _Nullable __autoreleasing * _Nullable)#>];

        [[AVAudioSession sharedInstance] setCategory:<#(nonnull NSString *)#>
                                                 mode:<#(nonnull NSString *)#>
                                   routeSharingPolicy:<#(AVAudioSessionRouteSharingPolicy)#>
                                              options:<#(AVAudioSessionCategoryOptions)#> 
                                                error:<#(NSError * _Nullable __autoreleasing * _Nullable)#>];

【苹果推荐使用】
        [[AVAudioSession sharedInstance] setCategory:<#(nonnull NSString *)#>
                                                mode:<#(nonnull NSString *)#>
                                             options:<#(AVAudioSessionCategoryOptions)#>
                                               error:<#(NSError * _Nullable __autoreleasing * _Nullable)#>];

         [[AVAudioSession sharedInstance] setCategory:<#(nonnull NSString *)#>
                                          withOptions:<#(AVAudioSessionCategoryOptions)#>
                                                error:<#(NSError * _Nullable __autoreleasing * _Nullable)#>];
  1. Category : NSString
  2. Model : NSString
  3. routeSharingPolicy : AVAudioSessionRouteSharingPolicy
  4. options : AVAudioSessionCategoryOptions
  5. error : NSError

SetActive

/* Set the session active or inactive. Note that activating an audio session is a synchronous (blocking) operation.
 Therefore, we recommend that applications not activate their session from a thread where a long blocking operation will be problematic.
 Note that this method will throw an exception in apps linked on or after iOS 8 if the session is set inactive while it has running or 
 paused I/O (e.g. audio queues, players, recorders, converters, remote I/Os, etc.).
*/
- (BOOL)setActive:(BOOL)active error:(NSError **)outError;
- (BOOL)setActive:(BOOL)active withOptions:(AVAudioSessionSetActiveOptions)options error:(NSError **)outError NS_AVAILABLE_IOS(6_0);

系统启动时会激活 AVAudioSession,通过设置active为"YES"激活Session,设置为“NO”解除Session的激活状态。
Options 使用 AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation 可使音频会话停用时,会话中断的其它音频会话可以返回到其它活动状态,于 SetAction:NO 成对儿使用。

    [[AVAudioSession sharedInstance] setActive:NO
                                   withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation
                                         error:nil];

也可通过

[AVAudioSession sharedInstance].otherAudioPlaying

进行判断当前是否有其他App在播放音频,从而进行其它业务处理

注意:

如果一个活动音频会话的优先级高于当前音频会话(如电话呼叫),并且两个音频会话都不允许混音,则激活音频会话将失败。
取消激活正在运行音频对象的音频会话,将停止正在运行的运行对象并取消激活会话,error 返回 AVAudioSessionErrorCodeIsBusy错误。(虽然报错,但是活动状态扔被更改成功为未激活)。


Category Property

#pragma mark -- Values for the category property --

/*  Use this category for background sounds such as rain, car engine noise, etc.  
 Mixes with other music. */
AVF_EXPORT NSString *const AVAudioSessionCategoryAmbient;

/*  Use this category for background sounds.  Other music will stop playing. */
AVF_EXPORT NSString *const AVAudioSessionCategorySoloAmbient;

/* Use this category for music tracks.*/
AVF_EXPORT NSString *const AVAudioSessionCategoryPlayback;

/*  Use this category when recording audio. */
AVF_EXPORT NSString *const AVAudioSessionCategoryRecord;

/*  Use this category when recording and playing back audio. */
AVF_EXPORT NSString *const AVAudioSessionCategoryPlayAndRecord;

/*  Use this category when using a hardware codec or signal processor while
 not playing or recording audio. */
AVF_EXPORT NSString *const AVAudioSessionCategoryAudioProcessing NS_DEPRECATED_IOS(3_0, 10_0) __TVOS_PROHIBITED __WATCHOS_PROHIBITED;

/*  Use this category to customize the usage of available audio accessories and built-in audio hardware.
 For example, this category provides an application with the ability to use an available USB output 
 and headphone output simultaneously for separate, distinct streams of audio data. Use of 
 this category by an application requires a more detailed knowledge of, and interaction with, 
 the capabilities of the available audio routes.  May be used for input, output, or both.
 Note that not all output types and output combinations are eligible for multi-route.  Input is limited
 to the last-in input port. Eligible inputs consist of the following:
    AVAudioSessionPortUSBAudio, AVAudioSessionPortHeadsetMic, and AVAudioSessionPortBuiltInMic.  
 Eligible outputs consist of the following: 
    AVAudioSessionPortUSBAudio, AVAudioSessionPortLineOut, AVAudioSessionPortHeadphones, AVAudioSessionPortHDMI, 
    and AVAudioSessionPortBuiltInSpeaker.  
 Note that AVAudioSessionPortBuiltInSpeaker is only allowed to be used when there are no other eligible 
 outputs connected.  */
AVF_EXPORT NSString *const AVAudioSessionCategoryMultiRoute NS_AVAILABLE_IOS(6_0);

AVAudioSessionCategoryAmbient : 此类别适用于‘伴奏模式’应用,例如用户在使用音乐应用播放时播放的伴奏。当使用该类别时,来自其他应用程序的音频会与当前的音频混合。屏幕锁定和Silent开关【静音开关】会使其静音。

AVAudioSessionCategorySoloAmbient : 系统默认会话类别。默认情况下,使用该类别意味着 应用程序的音频不可混合,激活应用中的会话将终止其它音频会话不可混合。如允许混合,则改用 AVAudioSessionCategoryAmbient

AVAudioSessionCategoryPlayback :用于播放录制音乐或者其它声音的类别。静音开关或者锁屏不会音响音频的播放。如要在应用程序转换到后台时继续播放(锁屏情况下)在xcode中设置 UIBackgroundModes 即可。默认情况下,使用此类别意味着,应用的音频不可混合,激活音频会话将中断其它不可混合的音频会话。如要使用混音,则使用 AVAudioSessionCategoryOptionMixWithOthers

AVAudioSessionCategoryRecord : 录制音频的类别,此类别使播放音频静音。只要该会话处于活动状态,此类别会使系统上的所有输出停止。除非需要防止播放其它的声音,否则建议使用 AVAudioSessionCategoryPlayAndRecord。要在应用程序在后台继续录制音频(锁屏情况)在xcode中设置 UIBackgroundModes 即可。

用户必须授权音频录制权限(iPhone 麦克风权限)。
此类别会话会被 电话呼叫、闹钟或者其它非混音音频会话中断

AVAudioSessionCategoryPlayAndRecord : 录音(输入)和播放(输出)音频的类别,例如VoIP(互联网语音协议)应用程序。
静音键开启和锁屏都不会影响音频继续播放。如要在应用程序转换到后台时继续播放(锁屏情况下)在xcode中设置 UIBackgroundModes 即可。此类别适用于同时录制和播放(语音连麦),也适用于录音/播放(IM语音条)。 但不能同时播放。默认情况下,使用此类别意味着应用程序的音频不可混合。激活会话将终端任何其他音频会话也是不可混合的。要允许为此类别混音,请使用AVAudioSessionCategoryOptionMixWithOthers选项

用户必须授权音频录制权限(iPhone 麦克风权限)
此类别支持Airplay的镜像版本。但是,如果AVAudioSessionModeVoiceChat模式与此类别一起使用,则AirPlay镜像将被禁用。

AVAudioSessionCategoryMultiRoute : 用于将不同音频数据流同时路由到不同输出设备的类别。此类别可用于输入,输出或两者。 例如,使用此类别将音频路由到USB设备和一组耳机。 使用这个类别需要对可用音频路由的功能有更详细的了解,并与之互动。
路由更改可能会使部分或全部多路由配置失效。 使用AVAudioSessionCategoryMultiRoute类别时,必须注册以观察AVAudioSessionRouteChangeNotification通知并根据需要更新配置。

可用于输入,输出或两者。
请注意,并非所有输出类型和输出组合都适用于多路径。输入是有限的
到最后一个输入端口。合格的输入包括以下内容:
AVAudioSessionPortUSBAudio,AVAudioSessionPortHeadsetMic和AVAudioSessionPortBuiltInMic。
符合条件的产出包括以下内容:
AVAudioSessionPortUSBAudio,AVAudioSessionPortLineOut,AVAudioSessionPortHeadphones,AVAudioSessionPortHDMI,
和AVAudioSessionPortBuiltInSpeaker。
请注意,AVAudioSessionPortBuiltInSpeaker只允许在没有其他符合条件时使用
输出连接。

1.常规播放

一般如果应用只有简单音乐播放功能,那么我们的AVAudioSession-Category只用像如下一样设置即可:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];     [[AVAudioSession sharedInstance] setActive:YES error:nil];

此时如果我们只是播放音乐,而不需要独占锁屏界面时,还可以设置:

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                     withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                           error:nil];

这样我们兼容其他后台播放的音乐一起进行播放,不过大部分场景下,我们是需要独占式后台播放。

2.常规录音

在录音的时候,我们一般如以下设置:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:nil];     
[[AVAudioSession sharedInstance] setActive:YES error:nil];

3.如果将录音和播放同时进行时,我们改选择何种Category?

同时进行播放和录音时,我们需要这样设置:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord                                            error:nil];     
[[AVAudioSession sharedInstance] setActive:YES error:nil];

需要注意的是,设置成这样的情况下,如果,在录音未开启的情况下,直接进行播放,则会出现,播放音量特别小的情况,我们需要在播放之前,将录音打开。

4.前后台切换

上述的模式,在iOS系统下,是不允许录音和播放在后台状态下同时进行的(PS:语音视频通话是通过CallKit实现的,不用于常规的播放和录音功能)。由此,我们在应用进入后台时就需要关掉其中一个功能。

以后台支持播放为例,在应用将要失活时,先切换模式,再关掉录音功能:

// stopRecording...

// 切换模式

  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
  [[AVAudioSession sharedInstance] setActive:YES error:nil];

应用即将进入前台时,切换模式,再开启录音功能:

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord                                            error:nil];
    [[AVAudioSession sharedInstance] setActive:YES                                          error:nil];

// 延迟恢复,否则会导致AVAudioSession的i/o错误

    [self performSelectorOnMainThread:@selector(startRecording) withObject:nil waitUntilDone:NO];

5.电话中断

电话闹钟的中断也会对,[AVAudioSession sharedInstance] 产生影响。

我们一般场景下会用 下面这个通知进行监控并处理暂停和恢复的工作:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:nil]; 
- (void)handleInterruption:(NSNotification*)notification { NSLog(@"interruption info:%@",notification.userInfo); }

但是,当我们在处理第四个场景前后台的情况下,这个通知,在中断的时候会进入,但是电话结束后,不会再接收到中断结束的通知。

原因:

有的app使用了AVCaptureDevice和AVCaptureSession,以进行录音录像操作。为了调优app设置,以更好的进行录音录像,从iOS7开始,在默认情况下,AVCaptureSession会使用app的AVAudioSession,并对其进行修改。这样,设置的中断监听方法会失效。

而电话来电也会使我们的应用接收到 失活的通知,在失活的时候处理了AVAudioSession,就会导致上述通知失效。

解决方案:我这里采用了比较折中的方案,因为我们的需求,对于第四条的处理是必要的。使用的是 CoreTelephony框架下的CTCallCenter对象,来监控电话的 拨入接通、挂断等状态。代码如下:

self.center = [[CTCallCenter alloc] init];
// TODO: 检测到来电后的处理
self.center.callEventHandler = ^(CTCall * call){
    if (call.callState == CTCallStateIncoming ||
        call.callState == CTCallStateConnected ||
        call.callState == CTCallStateDialing)
    {
    }
    else if (call.callState == CTCallStateDisconnected)
    {
    }
};

通过各种打电话的场景测试后,可以实现电话中断恢复功能。

ps:至于闹钟的中断以及siri等其他中断,暂时没有调研和实现。

6.蓝牙车载

终于来到了本文的最后一个部分了,也是最为曲折的一部分。

本来以为车载的车机连接后对于iPhone的播放控制与锁屏控制类似,直接在系统媒体远程控制监控中就能够拿到相应的控制方法回调。

在APPDelegate中加上如下代码:

//监听远程交互方法
- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    switch (event.subtype)
    {
            //播放
        case UIEventSubtypeRemoteControlPlay:
            break;
            //停止
        case UIEventSubtypeRemoteControlPause:
            break;
            //下一首
        case UIEventSubtypeRemoteControlNextTrack:
            break;
            //上一首
        case UIEventSubtypeRemoteControlPreviousTrack:
            break;
        default:
          break;
    }
}

事实上,当我们的应用只有简单的播放功能的时候,上述代码的确可以完美的实现车机对于播放的控制功能。但是当应用出于前台的情况下,我们添加上了一直录音的功能的时候,用车机控制播放,就完全没有任何响应了。可以注意到的是,我们看到车机的屏幕上,会显示通话中。查阅了各种资料和文章,都没有找到相关的解决办法和原理解释。

最后,想到了看看有没有其他类似的语音识别及播放功能的应用(iOS)有没有类似的处理,结果调研到百度地图 中的小度 有相关的处理。在它的设置中,找到 语音设置有一个蓝牙连接设置 。两个模式设置 如下:

a.蓝牙设备播报,小度无法唤醒使用(播放体验最佳)

b.蓝牙设备播报,小度唤醒正常使用(车机显示通话中,播报音量可能变小)

由此可以看出,a场景下 录音功能关闭,只有语音播报功能,b场景下,录音功能开启,车机就是会识别到手机设备在录音和播放中,认为就是在通话中,这个是车机本身的限制,无法从应用层进行优化。而且,百度地图的给用的默认选择就是,连接蓝牙的情况下,小度不能唤醒。

综合上面我们协同产品,从交互层面上更改,保证,在连接车机的情况下,能够控制播放。具体处理交互如下:

在应用进入到前台时,检测到连接了蓝牙设备,弹出弹框,让用户选择,继续开启唤醒功能开始,关闭唤醒功能(保证播放控制功能)。继续开启的情况下,车机无法控制播放。

下面是检测是否有输出设备连接的代码(并未找到检查当前是否有连接蓝牙设备的方法):

+ (BOOL)checkIsConnectToBluetooth
{
    BOOL isBluetooth = NO;
    // 找出当前所有支持输入的设备  availableInputs 这里面会出现 iPhone麦克风, 蓝牙耳机1, 蓝牙耳机2 , 三个对象, 在一个数组里.
    NSArray* inputArray = [[AVAudioSession sharedInstance] availableInputs];
    for (AVAudioSessionPortDescription* desc in inputArray)
    {
        if ([desc.portType isEqualToString:AVAudioSessionPortBluetoothLE] ||
            [desc.portType isEqualToString:AVAudioSessionPortBluetoothHFP] ||
            [desc.portType isEqualToString:AVAudioSessionPortBluetoothA2DP])
        {
            isBluetooth = YES;
        }
    }
    return isBluetooth;
}

同时,还需要配合Category的设置:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord                                          withOptions:AVAudioSessionCategoryOptionAllowBluetooth                                                error:&error];        
[[AVAudioSession sharedInstance] setActive:YES error:&error1];

AVAudioSessionCategoryOptionAllowBluetooth这是必须要添加的,否则上面的方法,连接蓝牙后,在应用即将活跃的监控的时候,是会返回NO,拿不到准确的值。


Mode Property

#pragma mark -- Values for the mode property --

/*!
@abstract      Modes modify the audio category in order to introduce behavior that is tailored to the specific
use of audio within an application.  Available in iOS 5.0 and greater.
 */

/* The default mode */
AVF_EXPORT NSString *const AVAudioSessionModeDefault NS_AVAILABLE_IOS(5_0);

/* Only valid with AVAudioSessionCategoryPlayAndRecord.  Appropriate for Voice over IP
(VoIP) applications.  Reduces the number of allowable audio routes to be only those
that are appropriate for VoIP applications and may engage appropriate system-supplied
signal processing.  Has the side effect of setting AVAudioSessionCategoryOptionAllowBluetooth */
AVF_EXPORT NSString *const AVAudioSessionModeVoiceChat NS_AVAILABLE_IOS(5_0);

/* Set by Game Kit on behalf of an application that uses a GKVoiceChat object; valid
 only with the AVAudioSessionCategoryPlayAndRecord category.
 Do not set this mode directly. If you need similar behavior and are not using
 a GKVoiceChat object, use AVAudioSessionModeVoiceChat instead. */
AVF_EXPORT NSString *const AVAudioSessionModeGameChat NS_AVAILABLE_IOS(5_0);

/* Only valid with AVAudioSessionCategoryPlayAndRecord or AVAudioSessionCategoryRecord.
 Modifies the audio routing options and may engage appropriate system-supplied signal processing. */
AVF_EXPORT NSString *const AVAudioSessionModeVideoRecording NS_AVAILABLE_IOS(5_0);

/* Appropriate for applications that wish to minimize the effect of system-supplied signal
processing for input and/or output audio signals. */
AVF_EXPORT NSString *const AVAudioSessionModeMeasurement NS_AVAILABLE_IOS(5_0);

/* Engages appropriate output signal processing for movie playback scenarios.  Currently
only applied during playback over built-in speaker. */
AVF_EXPORT NSString *const AVAudioSessionModeMoviePlayback NS_AVAILABLE_IOS(6_0);

/* Only valid with kAudioSessionCategory_PlayAndRecord. Reduces the number of allowable audio
routes to be only those that are appropriate for video chat applications. May engage appropriate
system-supplied signal processing.  Has the side effect of setting
AVAudioSessionCategoryOptionAllowBluetooth and AVAudioSessionCategoryOptionDefaultToSpeaker. */
AVF_EXPORT NSString *const AVAudioSessionModeVideoChat NS_AVAILABLE_IOS(7_0);

/* Appropriate for applications which play spoken audio and wish to be paused (via audio session interruption) rather than ducked
if another app (such as a navigation app) plays a spoken audio prompt.  Examples of apps that would use this are podcast players and
audio books.  For more information, see the related category option AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers. */
AVF_EXPORT NSString *const AVAudioSessionModeSpokenAudio NS_AVAILABLE_IOS(9_0);

音频会话的类别和模式一起定义应用打算如何使用音频。通常在激活会话之前设置类别和模式。但也可在会话处于活跃状态时设置类别模式,但这会导致立即更改。

建议使用setCategory:mode:options:error:method同时设置它们,而不是单独设置类别和模式属性。

AVAudioSessionModeDefault : 默认值

AVAudioSessionModeVoiceChat : 执行双向语音通信(如使用网际协议语音VoIP)则使用此模式。此模式适用于IP语音,并且只能与AVAudioSessionCategoryPlayAndRecord类别一起使用。使用此模式时,该设备的音调君合针对语音进行了优化,并且允许路线组仅缩小为适用于语音聊天的路线。此模式同事会启用AVAudioSessionCategoryOptionAllowBluetooth 类别选线支持蓝牙耳机。
如果应用程序未将其模式设置为其中一个聊天模式(语音,视频或游戏),则AVAudioSessionModeVoiceChat模式将被隐式设置。另一方面,如果应用程序先前已将其类别设置为AVAudioSessionCategoryPlayAndRecord并将其模式设置为AVAudioSessionModeVideoChatAVAudioSessionModeGameChat,则实例化语音处理I / O音频单元不会导致模式发生更改。

AVAudioSessionModeVideoChat : 在线视频会议,选定此模式。只能与AVAudioSessionCategoryPlayAndRecordAVAudioSessionCategoryRecord类别一起使用。使用此模式时,设备的音调均衡针对语音进行了优化,并且允许的音频路由组仅缩减为适合视频聊天的设置。
此模式同事会启用AVAudioSessionCategoryOptionAllowBluetooth类别选线支持蓝牙耳机。

AVAudioSessionModeGameChat : 该模式由Game Kit代表使用Game Kit的语音聊天服务的应用程序设置。
此模式仅适用于AVAudioSessionCategoryPlayAndRecord音频会话类别。
不要直接设置此模式。 如果需要类似的行为并且未使用GKVoiceChat对象,请改为使用AVAudioSessionModeVoiceChatAVAudioSessionModeVideoChat

AVAudioSessionModeVideoRecording : 适用于视频录制情景。此模式仅适用于 AVAudioSessionCategoryRecordAVAudioSessionCategoryPlayAndRecord音频会话类别。在具有多个内置麦克风的设备上,使用距摄像头最近的麦克风。此模式会导致系统提供适当的音频信号处理。将AVCaptureSession 与视频录制模式结合使用。可以很好的控制输入和输出路径。(设置自动配置应用音频会话属性会根据使用的设备和摄像机自动选择最佳输入路由。)

AVAudioSessionModeMeasurement : 如果应用正在执行音频输入或输出的测试。此模式适用于需要将输入和输出信号的系统提供的信号处理量将至最低的应用程序。如果在具有多个内置麦克风的设备上录制,则使用主麦克风。
用于AVAudioSessionCategoryPlaybackAVAudioSessionCategoryRecordAVAudioSessionCategoryPlayAndRecord音频会话类别。

AVAudioSessionModeMoviePlayback : 如果应用正在播放电影内容,请指定此模式。
使用此模式时,将采用信号处理来增强某些音频路由(如内置扬声器或耳机)的电影播放。 只能在AVAudioSessionCategoryPlayback音频会话类别中使用此模式。

AVAudioSessionModeSpokenAudio : 当想要在另一个应用播放短语音频时暂停当前音频时,用于持续说话音频的模式。
在iOS 8和更低版本以及iOS 9中,如果不设置此模式,偶尔从导航和应用程序中听到的语音与音频混合在一起,或造成两种音频的混淆。 此模式通过为中断应用程序使用AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers音频会话类别选项来避免此问题。 中断应用程序的音频结束后,可以恢复中断的语音。


AVAudioSessionCategoryOptions

typedef NS_OPTIONS(NSUInteger, AVAudioSessionCategoryOptions)
{
    /* MixWithOthers is only valid with AVAudioSessionCategoryPlayAndRecord, AVAudioSessionCategoryPlayback, and  AVAudioSessionCategoryMultiRoute */
    AVAudioSessionCategoryOptionMixWithOthers           = 0x1,
    /* DuckOthers is only valid with AVAudioSessionCategoryAmbient, AVAudioSessionCategoryPlayAndRecord, AVAudioSessionCategoryPlayback, and AVAudioSessionCategoryMultiRoute */
    AVAudioSessionCategoryOptionDuckOthers              = 0x2,
    /* AllowBluetooth is only valid with AVAudioSessionCategoryRecord and AVAudioSessionCategoryPlayAndRecord */
    AVAudioSessionCategoryOptionAllowBluetooth  __TVOS_PROHIBITED __WATCHOS_PROHIBITED      = 0x4,
    /* DefaultToSpeaker is only valid with AVAudioSessionCategoryPlayAndRecord */
    AVAudioSessionCategoryOptionDefaultToSpeaker __TVOS_PROHIBITED __WATCHOS_PROHIBITED     = 0x8,
    /* InterruptSpokenAudioAndMixWithOthers is only valid with AVAudioSessionCategoryPlayAndRecord, AVAudioSessionCategoryPlayback, and AVAudioSessionCategoryMultiRoute */
    AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers NS_AVAILABLE_IOS(9_0) = 0x11,
    /* AllowBluetoothA2DP is only valid with AVAudioSessionCategoryPlayAndRecord */
    AVAudioSessionCategoryOptionAllowBluetoothA2DP API_AVAILABLE(ios(10.0), watchos(3.0), tvos(10.0)) = 0x20,
    /* AllowAirPlay is only valid with AVAudioSessionCategoryPlayAndRecord */
    AVAudioSessionCategoryOptionAllowAirPlay API_AVAILABLE(ios(10.0), tvos(10.0)) __WATCHOS_PROHIBITED = 0x40,
} NS_AVAILABLE_IOS(6_0);

AVAudioSessionCategoryOptionMixWithOthers :确定来自此会话的音频是否与来自其他音频应用中活动会话的音频混合。

  • 只有在音频会话类别为AVAudioSessionCategoryPlayAndRecordAVAudioSessionCategoryPlaybackAVAudioSessionCategoryMultiRoute时,才能显式设置此选项。
  • 如果会话类别是AVAudioSessionCategoryAmbient,则此选项会自动设置。
  • 如果设置了AVAudioSessionCategoryOptionDuckOthersAVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers选项,则会自动设置此选项。
  • 如果清除此选项,激活会话会中断其他音频会话。 如果设置了此选项,则应用程序的音频会与后台应用程序中的音频(如音乐应用程序)混合在一起。

AVAudioSessionCategoryOptionDuckOthers : 当来自此会话的音频播放时,会导致来自其他会话的音频被降低(音量降低)。

  • 只有音频会话类别为AVAudioSessionCategoryPlayAndRecordAVAudioSessionCategoryPlaybackAVAudioSessionCategoryMultiRoute时,才能设置此选项。设置此标志隐式设置AVAudioSessionCategoryOptionMixWithOthers标志。
  • 如果清除此选项,激活会话会中断其他音频会话。
  • 如果设置了此选项,则应用程序的音频会与后台应用程序中的音频(如音乐应用程序)混合在一起。与当前应用混合时,来自其他应用的音频会减少音量。
  • 如果您希望通过音乐或其他当前正在播放的音频听到您应用中的音频(例如,导航应用中的语音提示),请设置此选项。如果您的应用程序提供了偶尔的口语音频,例如在转弯的导航应用程序或练习应用程序中,则还应该设置AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers选项。

AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers : 确定播放此应用的音频内容时,是否暂停了来自其他应用的连续语音内容。

  • 只有音频会话类别为AVAudioSessionCategoryPlayAndRecordAVAudioSessionCategoryPlaybackAVAudioSessionCategoryMultiRoute时,才能设置此选项。设置此选项还会设置AVAudioSessionCategoryOptionMixWithOthers
  • 如果清除此选项,音频会话中的音频会中断其他会话。如果设置了此选项,则您的音频会与其他音频会话混合使用,但会中断(并停止)使用AVAudioSessionModeSpokenAudio音频会话模式的音频会话。只要会话处于活动状态,其他应用程序的音频就会暂停。音频会话停用后,中断的应用程序的音频恢复。
  • 如果突然播放一段语音,例如导航应用,使用此选项。这可以避免两个口语音频应用程序混合时出现干扰问题。除非有特殊的原因,否则建议设置为AVAudioSessionCategoryOptionDuckOthers选项。当其他音频不是说音频时,避免其他音频而不是中断它。

AVAudioSessionCategoryOptionAllowBluetooth : 确定蓝牙免提设备是否显示为可用输入路由。
需要设置此选项才能将音频输入和输出路由到配对的蓝牙免提模式(HFP)设备。 如果清除此选项,则配对的蓝牙HFP不会显示为可用的音频输入路由。
如果应用程序使用setPreferredInput:error:方法选择蓝牙HFP输入,则输出将自动更改为相应的蓝牙HFP输出。 同样,使用MPVolumeView对象的路由选择器选择蓝牙HFP输出,会自动将输入更改为相应的蓝牙HFP输入。 因此,即使仅选择了输入或输出,音频输入和输出也将始终路由至Bluetooth HFP设备。
只有音频会话类别为AVAudioSessionCategoryPlayAndRecordAVAudioSessionCategoryRecord时,才能设置此选项。

AVAudioSessionCategoryOptionAllowBluetoothA2DP : 确定来自此会话的音频是否可以流式传输到支持高级音频分发配置文件(A2DP)的蓝牙设备。

高级音频分布配置文件(A2DP)是一种立体声,仅输出配置文件,适用于较高带宽音频使用情况,如音乐播放。如果应用程序的音频会话配置为使用AVAudioSessionCategoryAmbientAVAudioSessionCategorySoloAmbientAVAudioSessionCategoryPlayback类别,系统将自动路由至A2DP端口。
从iOS 10.0开始,使用AVAudioSessionCategoryPlayAndRecord类别的应用程序还可以允许将输出路由到配对的蓝牙A2DP设备。要启用此行为,您需要在设置音频会话的类别时传递此类别选项。
使用AVAudioSessionCategoryMultiRouteAVAudioSessionCategoryRecord类别的音频会话隐式清除此选项。如果清除此选项,则配对的蓝牙A2DP设备不会显示为可用的音频输出路由。

如果此选项和AVAudioSessionCategoryOptionAllowBluetooth选项均已设置,则当单个设备同时支持免提配置文件(HFP)和高级音频分布配置文件(A2DP)时,免提端口将获得更高的路由优先级。

AVAudioSessionCategoryOptionAllowAirPlay : 确定此会话中的音频是否可以传输到AirPlay设备。
只有在音频会话类别为AVAudioSessionCategoryPlayAndRecord时,才能显式设置此选项。 对于大多数其他音频会话类别,此选项是隐式设置的。 使用AVAudioSessionCategoryMultiRouteAVAudioSessionCategoryRecord类别的音频会话隐式清除此选项。
如果清除此选项,则AirPlay设备不会显示为可用的音频输出路线。 如果设置了此选项,这些设备将显示为可用的输出路径。

AVAudioSessionCategoryOptionDefaultToSpeaker : 确定会话中的音频是否默认为内置扬声器而不是接收器。
此选项只能在使用AVAudioSessionCategoryPlayAndRecord类别时设置。 它用于修改类别的路由行为,以便在没有使用其他配件(如耳机)的情况下,音频始终会路由至扬声器而不是接收器。
使用此选项时,用户手势将得到遵守。 例如,插入头戴式耳机将导致路由变为头戴式耳机麦克风/耳机,并且拔下头戴式耳机将导致路由更换为内置麦克风/扬声器(与内置麦克风/接收器相反) 已设置。
如果使用USB输入专用附件,音频输入将来自附件,如果没有插入耳机,则输出将路由到耳机(如果连接)或扬声器。


总结:

默认情况 :AVAudioSessionCategorySoloAmbient
播放IM音频:AVAudioSessionCategorySoloAmbient
设置录制IM音频:AVAudioSessionCategoryRecord
VoIP、网络电话会议:AVAudioSessionCategoryPlayAndRecord


Audio Session Error Codes

由AVAudioSession方法返回的NSError对象中使用的错误代码。

AVAudioSessionErrorCodeNone
操作成功。
AVAudioSessionErrorCodeMediaServicesFailed
尝试在媒体服务失败期间或之后使用音频会话。
AVAudioSessionErrorCodeIsBusy
尝试将其音频会话设置为非活动状态,但仍在播放和/或录制。
AVAudioSessionErrorCodeIncompatibleCategory
试图执行当前类别中不允许的操作。
AVAudioSessionErrorCodeCannotInterruptOthers
尝试在应用程序处于后台时使不可混音的音频会话处于活动状态。
AVAudioSessionErrorCodeMissingEntitlement
试图执行应用程序没有所需权利的操作。
AVAudioSessionErrorCodeSiriIsRecording
Siri正在录制时尝试执行不允许的操作。
AVAudioSessionErrorCodeCannotStartPlaying
试图开始音频播放,但不允许播放。
AVAudioSessionErrorCodeCannotStartRecording
试图开始录音,但失败了。
AVAudioSessionErrorCodeBadParam
试图将属性设置为非法值。
AVAudioSessionErrorInsufficientPriority
该应用程序不允许设置音频类别,因为它正在被另一个应用程序使用。
AVAudioSessionErrorCodeResourceNotAvailable
由于设备没有足够的硬件资源来完成操作而失败的操作。
AVAudioSessionErrorCodeUnspecified
没有更多的错误信息可用。当音频系统处于不一致状态时,通常会产生这种错误类型。

port types

#pragma mark -- constants for port types --

/* input port types */
AVF_EXPORT NSString *const AVAudioSessionPortLineIn       NS_AVAILABLE_IOS(6_0); /* Line level input on a dock connector */
AVF_EXPORT NSString *const AVAudioSessionPortBuiltInMic   NS_AVAILABLE_IOS(6_0); /* Built-in microphone on an iOS device */
AVF_EXPORT NSString *const AVAudioSessionPortHeadsetMic   NS_AVAILABLE_IOS(6_0); /* Microphone on a wired headset.  Headset refers to an
                                                                                   accessory that has headphone outputs paired with a
                                                                                   microphone. */

/* output port types */
AVF_EXPORT NSString *const AVAudioSessionPortLineOut          NS_AVAILABLE_IOS(6_0); /* Line level output on a dock connector */
AVF_EXPORT NSString *const AVAudioSessionPortHeadphones       NS_AVAILABLE_IOS(6_0); /* Headphone or headset output */
AVF_EXPORT NSString *const AVAudioSessionPortBluetoothA2DP    NS_AVAILABLE_IOS(6_0); /* Output on a Bluetooth A2DP device */
AVF_EXPORT NSString *const AVAudioSessionPortBuiltInReceiver  NS_AVAILABLE_IOS(6_0); /* The speaker you hold to your ear when on a phone call */
AVF_EXPORT NSString *const AVAudioSessionPortBuiltInSpeaker   NS_AVAILABLE_IOS(6_0); /* Built-in speaker on an iOS device */
AVF_EXPORT NSString *const AVAudioSessionPortHDMI             NS_AVAILABLE_IOS(6_0); /* Output via High-Definition Multimedia Interface */
AVF_EXPORT NSString *const AVAudioSessionPortAirPlay          NS_AVAILABLE_IOS(6_0); /* Output on a remote Air Play device */
AVF_EXPORT NSString *const AVAudioSessionPortBluetoothLE      NS_AVAILABLE_IOS(7_0); /* Output on a Bluetooth Low Energy device */

/* port types that refer to either input or output */
AVF_EXPORT NSString *const AVAudioSessionPortBluetoothHFP NS_AVAILABLE_IOS(6_0); /* Input or output on a Bluetooth Hands-Free Profile device */
AVF_EXPORT NSString *const AVAudioSessionPortUSBAudio     NS_AVAILABLE_IOS(6_0); /* Input or output on a Universal Serial Bus device */
AVF_EXPORT NSString *const AVAudioSessionPortCarAudio     NS_AVAILABLE_IOS(7_0); /* Input or output via Car Audio */

#pragma mark -- constants for data source locations, orientations, polar patterns, and channel roles --

/* The following represent the location of a data source on an iOS device. */
AVF_EXPORT NSString *const AVAudioSessionLocationUpper                  NS_AVAILABLE_IOS(7_0);
AVF_EXPORT NSString *const AVAudioSessionLocationLower                  NS_AVAILABLE_IOS(7_0);

/* The following represent the orientation or directionality of a data source on an iOS device. */
AVF_EXPORT NSString *const AVAudioSessionOrientationTop                 NS_AVAILABLE_IOS(7_0);
AVF_EXPORT NSString *const AVAudioSessionOrientationBottom              NS_AVAILABLE_IOS(7_0);
AVF_EXPORT NSString *const AVAudioSessionOrientationFront               NS_AVAILABLE_IOS(7_0);
AVF_EXPORT NSString *const AVAudioSessionOrientationBack                NS_AVAILABLE_IOS(7_0);
AVF_EXPORT NSString *const AVAudioSessionOrientationLeft                NS_AVAILABLE_IOS(8_0);
AVF_EXPORT NSString *const AVAudioSessionOrientationRight               NS_AVAILABLE_IOS(8_0);

/* The following represent the possible polar patterns for a data source on an iOS device. */
AVF_EXPORT NSString *const AVAudioSessionPolarPatternOmnidirectional    NS_AVAILABLE_IOS(7_0);
AVF_EXPORT NSString *const AVAudioSessionPolarPatternCardioid           NS_AVAILABLE_IOS(7_0);
AVF_EXPORT NSString *const AVAudioSessionPolarPatternSubcardioid        NS_AVAILABLE_IOS(7_0);

转自:https://www.jianshu.com/p/ae843162ace1

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值