AVAudioSession - Detailed Explanation of Category, Model, Options, Error Parameters

[AVAudioSession sharedInstance] five setting methods

         [[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);

The AVAudioSession will be activated when the system starts, the Session can be activated by setting active to "YES", and the activation state of the Session can be deactivated by setting it to "NO".
When Options is used  AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation to disable the audio session, other audio sessions interrupted by the session can be returned to other active states, used in pairs with SetAction:NO.

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

also available through

[AVAudioSession sharedInstance].otherAudioPlaying

Determine whether other apps are currently playing audio, so as to perform other business processing

Notice:

If an active audio session has a higher priority than the current audio session (such as a phone call), and neither audio session allows audio mixing, activating the audio session will fail.
Deactivate the audio session of the running audio object, will stop the running running object and deactivate the session, error returns  AVAudioSessionErrorCodeIsBusyan error. (Although an error is reported, the active state is successfully changed to inactive).


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  : This category is suitable for 'accompaniment mode' applications, such as the accompaniment that the user plays while using the music application. When using this category, audio from other applications is mixed with the current audio. Screen lock and Silent switch 【Mute switch】 will make it silent.

AVAudioSessionCategorySoloAmbient  : The system default session category. By default, using this class means that the app's audio is not mixable, and activating a session in the app will terminate other audio sessions from being mixable. If mixing is permitted, use instead  AVAudioSessionCategoryAmbient.

AVAudioSessionCategoryPlayback  : A category for playing recorded music or other sounds. Mute switch or lock screen will not play audio. If you want to continue playing when the application is switched to the background (in the case of lock screen), you can set UIBackgroundModes in xcode. By default, using this class means that the app's audio is not mixable, and activating an audio session will interrupt other non-mixable audio sessions. If you want to use the audio mix, use  AVAudioSessionCategoryOptionMixWithOthers.

AVAudioSessionCategoryRecord  : The category of recording audio, this category mutes playback audio. This category stops all output on the system as long as the session is active. Recommended unless you need to prevent other sounds from being played  AVAudioSessionCategoryPlayAndRecord. To continue recording audio while the app is in the background (lock screen situation), set UIBackgroundModes in xcode.

User must authorize audio recording permission (iPhone microphone permission).
Sessions in this category are interrupted by phone calls, alarm clocks, or other non-mixed audio sessions

AVAudioSessionCategoryPlayAndRecord  : A category for recording (input) and playing (output) audio, such as a VoIP (Voice over Internet Protocol) application.
Turning on the mute button and locking the screen will not affect the audio to continue playing. If you want to continue playing when the application is switched to the background (in the case of lock screen), you can set UIBackgroundModes in xcode. This category is suitable for simultaneous recording and playback (voice mic), and also for recording/playback (IM voice bar). but not simultaneously. By default, using this class means that the application's audio is not mixable. Activating a session will terminate any other audio session which is also unmixable. To allow mixing for this category, use AVAudioSessionCategoryOptionMixWithOthersthe option

The user must authorize the audio recording permission (iPhone microphone permission).
This category supports the mirror version of Airplay. However, if AVAudioSessionModeVoiceChatthe mode is used with this category, AirPlay mirroring will be disabled.

AVAudioSessionCategoryMultiRoute  : A category for routing different audio data streams to different output devices simultaneously. This category can be used for input, output or both. For example, use this category to route audio to USB devices and a set of headphones. Using this category requires a more detailed understanding of, and interaction with, the functionality of the available audio routes.
Routing changes may invalidate some or all of the multi-routing configuration. When using AVAudioSessionCategoryMultiRouteclasses, you must register to observe AVAudioSessionRouteChangeNotificationnotifications and update configuration as necessary.

Can be used for input, output or both.
Note that not all output types and output combinations are suitable for multipathing. Input is limited
to the last input port. Eligible inputs include the following:
AVAudioSessionPortUSBAudio, AVAudioSessionPortHeadsetMic, and AVAudioSessionPortBuiltInMic.
Eligible outputs include the following:
AVAudioSessionPortUSBAudio, AVAudioSessionPortLineOut, AVAudioSessionPortHeadphones, AVAudioSessionPortHDMI,
and AVAudioSessionPortBuiltInSpeaker.
Note that AVAudioSessionPortBuiltInSpeaker only allows the use of an output connection when no other qualifies
.

1. Regular play

Generally, if the application only has a simple music playback function, then our AVAudioSession-Category only needs to be set as follows:

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

At this time, if we just play music and do not need to monopolize the lock screen interface, we can also set:

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

In this way, we are compatible with other music played in the background to play together, but in most scenarios, we need exclusive background playback.

2. Regular recording

When recording, we generally set as follows:

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

3. If recording and playback are performed at the same time, what category should we choose?

When playing and recording at the same time, we need to set it like this:

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

It should be noted that if the setting is set like this, if the recording is not turned on and the playback is performed directly, there will be a situation where the playback volume is extremely low, and we need to turn on the recording before playing.

4. Front and back switch

The above mode, under the iOS system, does not allow recording and playback to be performed simultaneously in the background (PS: voice and video calls are implemented through CallKit, not used for conventional playback and recording functions). Therefore, we need to turn off one of the functions when the application enters the background.

Taking background playback as an example, when the application is about to be deactivated, switch the mode first, and then turn off the recording function:

// stopRecording...

// toggle mode

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

When the application is about to enter the foreground, switch the mode, and then enable the recording function:

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

// delay recovery, otherwise it will cause i/o error of AVAudioSession

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

5. Call interruption

The interruption of the phone alarm clock will also affect [AVAudioSession sharedInstance].

In general, we will use the following notification to monitor and handle the work of suspending and resuming:

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

However, when we are dealing with the foreground and background of the fourth scene, this notification will enter during the interruption, but after the call is over, the notification of the end of the interruption will not be received again.

reason:

Some apps use AVCaptureDevice and AVCaptureSession for audio and video operations. In order to tune the app settings for better recording and video recording, starting from iOS7, by default, AVCaptureSession will use the app's AVAudioSession and modify it. In this way, the set interrupt monitoring method will be invalid.

The incoming phone call will also cause our application to receive an inactivation notification, and processing the AVAudioSession during inactivation will cause the above notification to become invalid.

Solution: I have adopted a compromise solution here, because of our needs, it is necessary to deal with the fourth article. The CTCallCenter object under the CoreTelephony framework is used to monitor the status of dial-in connection and hang-up. code show as below:

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)
    {
    }
};

After passing various phone call scene tests, the call interruption recovery function can be realized.

ps: As for the interruption of the alarm clock and other interruptions such as siri, there is no research and implementation yet.

6. Bluetooth car

Finally came to the last part of this article, which is also the most tortuous part.

I originally thought that after the car machine is connected, the playback control of the iPhone is similar to the lock screen control, and the corresponding control method callback can be obtained directly in the system media remote control monitoring.

Add the following code to APPDelegate:

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

In fact, when our application only has a simple playback function, the above code can indeed perfectly realize the control function of the car machine for playback. But when the app is in the foreground, when we add the function of continuous recording, there is no response at all when using the car to control the playback. It can be noticed that we can see that the call is displayed on the screen of the car. After consulting various materials and articles, no relevant solutions and principle explanations were found.

Finally, I thought of seeing if there are other similar voice recognition and playback applications (iOS) that have similar processing. As a result, I found that Xiaodu in Baidu Maps has related processing. In its settings, find the voice settings and there is a bluetooth connection setting. The two modes are set as follows:

a. The Bluetooth device broadcasts, and Xiaodu cannot be woken up to use (best playback experience)

b. The bluetooth device broadcasts, Xiaodu wakes up to normal use (the car machine shows that the call is in progress, the broadcast volume may become smaller)

It can be seen from this that in scenario a, the recording function is turned off, and only the voice broadcast function is available. In scenario b, the recording function is turned on, and the car will recognize that the mobile device is recording and playing, and it will be considered to be in a call. This is the car phone Due to its own limitations, it cannot be optimized from the application layer. Moreover, the default choice for Baidu Maps is that Xiaodu cannot be woken up when connected to Bluetooth.

Based on the above, we collaborated on the products and changed them from the interactive level to ensure that the playback can be controlled when the car is connected. The specific processing interaction is as follows:

When the application enters the foreground, it detects that a Bluetooth device is connected, and a pop-up box pops up for the user to choose, continue to enable the wake-up function to start, and disable the wake-up function (to ensure the playback control function). When it continues to be turned on, the car machine cannot control the playback.

The following is the code to detect whether there is an output device connected (I did not find a way to check whether there is a Bluetooth device currently connected):

+ (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;
}

At the same time, it also needs to cooperate with the setting of Category:

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

AVAudioSessionCategoryOptionAllowBluetooth must be added, otherwise, the above method, after connecting to Bluetooth, will return NO when the application is about to be actively monitored, and the accurate value cannot be obtained.


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);

Together, the audio session's class and mode define how the app intends to use audio. Usually the category and mode are set before activating the session. But it is also possible to set the category mode while the session is active, but this results in an immediate change.

It is recommended to use the setCategory:mode:options:error:method to set them at the same time, rather than setting category and mode properties separately.

AVAudioSessionModeDefault  : default value

AVAudioSessionModeVoiceChat  : Use this mode when performing two-way voice communication, such as using Voice over Internet Protocol (VoIP). This mode is for voice over IP and can only AVAudioSessionCategoryPlayAndRecordbe used with classes. When using this mode, the device's tones are optimized for voice and allow the set of routes to be narrowed down to only those suitable for voice chat. This mode will also enable AVAudioSessionCategoryOptionAllowBluetooth category selection to support Bluetooth headsets.
If the application does not set its mode to one of the chat modes (voice, video or game), the AVAudioSessionModeVoiceChatmode will be set implicitly. On the other hand, if the application has previously set its class to AVAudioSessionCategoryPlayAndRecordand its mode to AVAudioSessionModeVideoChator AVAudioSessionModeGameChat, instantiating the Speech Processing I/O audio unit does not cause the mode to change.

AVAudioSessionModeVideoChat  : Select this mode for online video conferencing. Can only be used with AVAudioSessionCategoryPlayAndRecordor AVAudioSessionCategoryRecordclasses. When using this mode, the device's tonal balance is optimized for voice, and the set of allowed audio routing is reduced only to settings suitable for video chats.
This mode will also enable AVAudioSessionCategoryOptionAllowBluetoothcategory selection to support Bluetooth headsets.

AVAudioSessionModeGameChat  : This mode is set by Game Kit on behalf of applications that use Game Kit's voice chat service.
This mode is only available for AVAudioSessionCategoryPlayAndRecordthe audio session category.
Do not set this mode directly. AVAudioSessionModeVoiceChatIf similar behavior is desired and the GKVoiceChat object is not used, use or instead AVAudioSessionModeVideoChat.

AVAudioSessionModeVideoRecording  : Suitable for video recording scenarios. This mode is only available for  the AVAudioSessionCategoryRecordand AVAudioSessionCategoryPlayAndRecordAudio Session categories. On devices with multiple built-in microphones, use the one closest to the camera. This mode causes the system to provide appropriate audio signal processing. Will be AVCaptureSession used in conjunction with video recording mode. The input and output paths can be well controlled. (Setting the AutoConfig App Audio Session property automatically selects the best input route based on the device and camera used.)

AVAudioSessionModeMeasurement  : If the app is performing a test of audio input or output. This mode is suitable for applications that require the minimum amount of signal processing provided by the system for input and output signals. If recording on a device with multiple built-in microphones, the primary microphone is used.
for AVAudioSessionCategoryPlayback, AVAudioSessionCategoryRecordor AVAudioSessionCategoryPlayAndRecordaudio session category.

AVAudioSessionModeMoviePlayback  : Specify this mode if the app is playing movie content.
When using this mode, signal processing is employed to enhance movie playback for certain audio routes such as internal speakers or headphones. This mode can only AVAudioSessionCategoryPlaybackbe used in the Audio Session category.

AVAudioSessionModeSpokenAudio  : Mode for continuous speaking audio when you want to pause the current audio while another app is playing the spoken audio.
In iOS 8 and earlier, as well as iOS 9, without setting this mode, occasionally speech heard from navigation and apps mixed with the audio, or caused confusion between the two. AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthersThis mode avoids this problem by using the audio session class option for interrupting applications . Interrupted speech can be resumed after the interrupted app's audio ends.


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  : Determines whether audio from this session is mixed with audio from active sessions in other audio applications.

  • This option can only be explicitly set if the audio session class is AVAudioSessionCategoryPlayAndRecord, AVAudioSessionCategoryPlaybackor .AVAudioSessionCategoryMultiRoute
  • AVAudioSessionCategoryAmbientThis option is automatically set if the session category is .
  • AVAudioSessionCategoryOptionDuckOthersThis option is automatically set if the or option is set AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers.
  • If this option is cleared, activating a session interrupts other audio sessions. If this option is set, the app's audio is mixed with audio from background apps, such as music apps.

AVAudioSessionCategoryOptionDuckOthers  : Causes audio from other sessions to be lowered (volume down) while audio from this session is playing.

  • This option can only be set if the audio session class is AVAudioSessionCategoryPlayAndRecord, AVAudioSessionCategoryPlaybackor AVAudioSessionCategoryMultiRoute. Setting this flag implicitly sets AVAudioSessionCategoryOptionMixWithOthersthe flag.
  • If this option is cleared, activating a session interrupts other audio sessions.
  • If this option is set, the app's audio is mixed with audio from background apps, such as music apps. Audio from other apps is reduced in volume when mixed with the current app.
  • Set this option if you want to hear audio in your app over music or other currently playing audio (for example, spoken prompts in a navigation app). You should also set the option if your app provides occasional spoken audio, such as in a turn-by-turn navigation app or practice app AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers.

AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers  : Determines whether continuous speech content from other apps is paused while playing this app's audio content.

  • This option can only be set if the audio session class is AVAudioSessionCategoryPlayAndRecord, AVAudioSessionCategoryPlaybackor AVAudioSessionCategoryMultiRoute. Setting this option also sets AVAudioSessionCategoryOptionMixWithOthers.
  • If this option is cleared, audio in an audio session interrupts other sessions. If this option is set, your audio is mixed with other audio sessions, but AVAudioSessionModeSpokenAudioaudio sessions using audio session mode are interrupted (and stopped). Audio from other applications is paused as long as the session is active. After the audio session is deactivated, the interrupted app's audio resumes.
  • Use this option if a voice is played suddenly, such as in a navigation app. This avoids interference issues when two spoken audio applications are mixed. Unless there is a special reason, it is recommended to set it as AVAudioSessionCategoryOptionDuckOthersan option. Avoid other audio instead of interrupting it when other audio is not speaking audio.

AVAudioSessionCategoryOptionAllowBluetooth  : Determines whether Bluetooth handsfree devices are shown as available input routes.
This option needs to be set to route audio input and output to a paired Bluetooth Hands-Free Profile (HFP) device. If this option is cleared, paired Bluetooth HFP will not appear as an available audio input route.
If the application setPreferredInput:error:selects the Bluetooth HFP input using the method, the output will automatically change to the corresponding Bluetooth HFP output. Likewise, selecting a Bluetooth HFP output using the MPVolumeView object's route selector automatically changes the input to the corresponding Bluetooth HFP input. Therefore, audio input and output will always be routed to the Bluetooth HFP device, even if only input or output is selected.
This option can only be set if the audio session class is AVAudioSessionCategoryPlayAndRecordor AVAudioSessionCategoryRecord.

AVAudioSessionCategoryOptionAllowBluetoothA2DP  : Determines whether audio from this session can be streamed to Bluetooth devices that support the Advanced Audio Distribution Profile (A2DP).

Advanced Audio Distribution Profile (A2DP) is a stereo, output-only profile intended for higher bandwidth audio use cases such as music playback. If the app's audio session is configured to use the AVAudioSessionCategoryAmbient, AVAudioSessionCategorySoloAmbientor AVAudioSessionCategoryPlaybackclass, the system will automatically route to the A2DP port.
Beginning with iOS 10.0, AVAudioSessionCategoryPlayAndRecordapps using categories can also allow routing of output to paired Bluetooth A2DP devices. To enable this behavior, you need to pass this class option when setting the audio session's class. This option is implicitly cleared
with an audio session of AVAudioSessionCategoryMultiRouteor class. AVAudioSessionCategoryRecordIf this option is cleared, paired Bluetooth A2DP devices will not appear as available audio output routes.

If both this option and AVAudioSessionCategoryOptionAllowBluetooththe option are set, the handsfree port will get higher routing priority when a single device supports both Handsfree Profile (HFP) and Advanced Audio Distribution Profile (A2DP).

AVAudioSessionCategoryOptionAllowAirPlay  : Determines whether audio in this session can be streamed to AirPlay devices.
This option can only be set explicitly AVAudioSessionCategoryPlayAndRecordif the audio session class is . For most other audio session classes, this option is set implicitly. This option is implicitly cleared with an audio session of AVAudioSessionCategoryMultiRouteor class. If this option is cleared, AirPlay devices will not appear as available audio output routes. If this option is set, these devices will be shown as available output paths.AVAudioSessionCategoryRecord

AVAudioSessionCategoryOptionDefaultToSpeaker  : Determines whether in-session audio defaults to the built-in speaker instead of the sink.
This option can only be set when using the AVAudioSessionCategoryPlayAndRecord category. It is used to modify the routing behavior of the class so that when no other accessories (such as headphones) are used, the audio is always routed to the speaker instead of the receiver.
When using this option, user gestures will be respected. For example, plugging in a headset will cause the routing to change to headset mic/headphone, and unplugging the headset will cause the routing to change to internal mic/speaker (as opposed to internal mic/receiver) as set.
If using a USB input dedicated accessory, the audio input will come from the accessory, and if no headphones are plugged in, the output will be routed to headphones (if connected) or speakers.


Summarize:

Default: AVAudioSessionCategorySoloAmbient
Play IM audio: AVAudioSessionCategorySoloAmbient
Set to record IM audio: AVAudioSessionCategoryRecord
VoIP, Internet conference call: AVAudioSessionCategoryPlayAndRecord


Audio Session Error Codes

The error code used in the NSError object returned by the AVAudioSession methods.

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);

Reposted from: https://www.jianshu.com/p/ae843162ace1

Guess you like

Origin blog.csdn.net/BUG_delete/article/details/123990617