AVAudioSession

Important

This is a preliminary document for an API or technology in development. Apple is supplying this information to help you plan for the adoption of the technologies and programming interfaces described herein for use on Apple-branded products. This information is subject to change, and software implemented according to this document should be tested with final operating system software and final documentation. Newer versions of this document may be provided with future betas of the API or technology.

An instance of the AVAudioSession class, called an audio session, is a singleton object that you employ to set the audio context for your app.

Use this class to:

Activate or deactivate your app’s audio session

Set the audio session category and mode in order to communicate to the system how you intend to use audio in your app

Configure audio settings such as sample rate, I/O buffer duration, and number of channels

Handle audio route changes

React to important audio events, such as changes to the availability of the underlying Media Services daemon

Configuring the Audio Session

The shared audio session object acts as an intermediary between your app and the system’s media services daemon (and in turn, the underlying audio hardware). The media service is subject to requests from other apps—some of which may have a higher priority than your app’s audio needs, such as handling a phone call. Because of the intermediary role that the media services daemon plays, your app does not directly control certain audio settings; instead, you request preferred values for these settings and observe properties on the AVAudioSession object (or related port and data source objects) to see whether, when, and to what extent your requests take effect.

If an audio route change occurs (due to such events as a phone call or audio in use by another app while yours is in the background), you may need to reapply your preferred audio settings. Subscribe to the AVAudioSessionRouteChangeNotification notification to respond to these events.

Preferred settings may not take effect immediately. For example, you can use the setPreferredDataSource:error: method on the built-in microphone port to select the front microphone while a headset is plugged in—this preference does not take effect until the headset is unplugged and the audio route changes.

Routing and Mixing

Your session’s category helps to determine audio input and output behaviors when multiple sessions are active. Other active sessions may be associated with system services (such as the Music app, turn-by-turn navigation, or a phone call) or background apps that support audio (see App States and Multitasking).

The system allows only one session to control audio routing. If multiple sessions are active, the system chooses which one controls routing based on priority (system sessions such as a phone call may supersede your app’s session) and whether the session is mixable.

Recording Requires User Permission

Recording audio requires explicit permission from the user. The first time your app’s audio session attempts to use an audio input route while using a category that enables recording, the system automatically prompts the user for permission. In iOS 7.0 and earlier, call requestRecordPermission: to prompt the user at a time of your choosing (see “Audio Session Categories”).

In iOS 8.0 and later, the user will not be asked to grant permission until the application attempt to use audio input.

After the user grants or denies permission, the system remembers the choice for future use in the same app. If the user has denied your app recoding permission or has not yet responded to the permission prompt, any audio recording sessions record only silence.

Media Services Availability

In iOS, the system provides audio and other multimedia functionality through a shared server process. Under certain circumstances, the system may terminate and restart this process. Your app should be prepared to respond to these events by reinitializing any audio objects in use (such as players, recorders, converters, or audio queues) in use and reapplying preferred audio session settings.

Declaration

Parameters

response

A block to be called when recording permission has been granted or denied.

Discussion

Recording audio requires explicit permission from the user. The system automatically prompts the user for permission if you use any session categories that enable recording. Or you can call this method to prompt for permission at a time of your choosing. After the user grants or denies permission, the system remembers the choice for future use in the same app. If permission is not granted, or if the user has not yet responded to the permission prompt, any audio recording sessions record only silence.

The response parameter is a block of the PermissionBlock type, whose sole parameter indicates whether the user granted or denied permission to record. This method always returns immediately. If the user has previously granted or denied recording permission, it executes the block when called; otherwise, it displays an alert and executes the block only after the user has responded to the alert.

Parameters

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YEStrue if the category and options were set successfully, or NOfalse otherwise.

Discussion

The session's category and mode together define how the application intends to use audio. Typically, you set the category and mode before activating the session. You can also set the category or mode while the session is active, but this results in an immediate route change.

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YEStrue if the category and options were set successfully, or NOfalse otherwise.

Discussion

The session's category and mode together define how the application intends to use audio. Typically, you set the category and mode before activating the session. You can also set the category or mode while the session is active, but this results in an immediate route change.

Import Statement

Objective-C

@import AVFoundation;

Swift

import AVFoundation

Availability

Declaration

Discussion

One of the constants listed in Audio Session Modes, which together with the audio session’s category indicates to the system how you intend to use audio in your app. You can use a mode to configure the audio system for specific use cases such as video recording, voice or video chat, or taking measurements. The default mode is AVAudioSessionModeDefault.

Parameters

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

Returns YEStrue on success or NOfalse on failure.

Discussion

The session's category and mode together define how the application intends to use audio. Typically, you set the category and mode before activating the session. You can also set the category or mode while the session is active, but this results in an immediate route change.

Discussion

The audio I/O buffer duration is the number of seconds for a single audio input/output cycle. For example, with an I/O buffer duration of 0.005 s, on each audio I/O cycle:

You receive 0.005 s of audio if obtaining input.

You must provide 0.005 s of audio if providing output.

The typical maximum I/O buffer duration is 0.93 s (corresponding to 4096 sample frames at a sample rate of 44.1 kHz). The minimum I/O buffer duration is at least 0.005 s (256 frames) but may be lower depending on the hardware in use.

You can set a preferred I/O buffer duration before or after activating the audio session.

Availability

See Also

A Boolean value that indicates whether another application is playing audio. (read-only)

Declaration

Swift

var secondaryAudioShouldBeSilencedHint: Bool { get }

Objective-C

@property(readonly)BOOLsecondaryAudioShouldBeSilencedHint

Discussion

The value is YEStrue when another application with a non-mixable audio session is playing audio.

Applications should use this property as a hint to silence audio that is secondary to the functionality of the application. For example, a game using AVAudioSessionCategoryAmbient may use this property to decide to mute its soundtrack while leaving its sound effects unmuted.

Parameters

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YEStrue if the new routing option was set successfully, or NOfalse if it was not.

Discussion

Calling this method with the AVAudioSessionPortOverrideSpeaker option and the audio session’s category AVAudioSessionCategoryPlayAndRecord causes audio to use the built-in speaker and microphone regardless of other settings. This change remains in effect only until the current route changes or you call this method again with the AVAudioSessionPortOverrideNone option.

Apple recommends using the MPVolumeView class to provide user control for audio input and output selection.

Declaration

Discussion

An array of AVAudioSessionPortDescription objects representing audio input devices currently attached to the system and relevant to the audio session’s current category and mode. For example, if the session’s category is AVAudioSessionCategoryPlayAndRecord, the array may contain a built-in microphone and (if plugged in) a headset microphone port.

Declaration

Discussion

The value of this property indicates the input port selected using the setPreferredInput:error: method. To see the actual current input port, use the currentRoute property. Returns nil if no preference has been set or if the previously set preferred input is no longer available.

The value of the inPort parameter must be one of the AVAudioSessionPortDescription objects in the availableInputs array. If this parameter specifies a port that is not already part of the current audio route and the app’s session controls audio routing, this method initiates a route change to use the preferred port.

You must set a preferred input port only after setting the audio session’s category and mode and activating the session.

Declaration

Discussion

An array of AVAudioSessionDataSourceDescription objects representing available input sources, or nil if switching between multiple input sources is not currently possible. This feature is supported only on certain devices and peripherals–for example, on an iPhone equipped with both front- and rear-facing microphones.

Declaration

Discussion

The value of this property is nil if switching between multiple input sources is not currently possible. This feature is supported only on certain devices and peripherals–for example, on an iPhone equipped with both front- and rear-facing microphones.

Parameters

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YEStrue if the input data source for the audio session was successfully assigned; otherwise, NOfalse.

Discussion

You may change the input source to just one of the AVAudioSessionDataSourceDescription objects in the inputDataSources array. Switching between multiple input sources is supported only on certain devices and peripherals; for example, this method can be used to choose between front- and rear-facing microphones on an iPhone equipped with them.

Declaration

Discussion

An array of AVAudioSessionDataSourceDescription objects representing available output sources, or nil if switching between multiple output sources is not currently possible. This feature is supported only on certain USB accessories.

Constants

AVAudioSessionCategoryAmbient

AVAudioSessionCategoryAmbient

The category for an app in which sound playback is nonprimary—that is, your app can be used successfully with the sound turned off.

This category is also appropriate for “play along” style apps, such as a virtual piano that a user plays while the Music app is playing. When you use this category, audio from other apps mixes with your audio. Your audio is silenced by screen locking and by the Silent switch (called the Ring/Silent switch on iPhone).

Your audio is silenced by screen locking and by the Silent switch (called the Ring/Silent switch on iPhone).

By default, using this category implies that your app’s audio is nonmixable—activating your session will interrupt any other audio sessions which are also nonmixable. To allow mixing, use the AVAudioSessionCategoryAmbient category instead.

Available in iOS 3.0 and later.

AVAudioSessionCategoryPlayback

AVAudioSessionCategoryPlayback

The category for playing recorded music or other sounds that are central to the successful use of your app.

When using this category, your app audio continues with the Silent switch set to silent or when the screen locks. (The switch is called the Ring/Silent switch on iPhone.) To continue playing audio when your app transitions to the background (for example, when the screen locks), add the audio value to the UIBackgroundModes key in your information property list file.

By default, using this category implies that your app’s audio is nonmixable—activating your session will interrupt any other audio sessions which are also nonmixable. To allow mixing for this category, use the AVAudioSessionCategoryOptionMixWithOthers option.

Available in iOS 3.0 and later.

AVAudioSessionCategoryRecord

AVAudioSessionCategoryRecord

The category for recording audio; this category silences playback audio.

To continue recording audio when your app transitions to the background (for example, when the screen locks), add the audio value to the UIBackgroundModes key in your information property list file.

The category for recording (input) and playback (output) of audio, such as for a VoIP (Voice over Internet Protocol) app.

Your audio continues with the Silent switch set to silent and with the screen locked. (The switch is called the Ring/Silent switch on iPhone.) To continue playing audio when your app transitions to the background (for example, when the screen locks), add the audio value to the UIBackgroundModes key in your information property list file.

This category is appropriate for simultaneous recording and playback, and also for apps that record and play back but not simultaneously.

By default, using this category implies that your app’s audio is nonmixable—activating your session will interrupt any other audio sessions which are also nonmixable. To allow mixing for this category, use the AVAudioSessionCategoryOptionMixWithOthers option.

Audio processing does not normally continue when your app is in the background. However, when your app moves to the background, you can request additional time to complete processing. For more information, see App Programming Guide for iOS.

Available in iOS 3.1 and later.

AVAudioSessionCategoryMultiRoute

AVAudioSessionCategoryMultiRoute

The category for routing distinct streams of audio data to different output devices at the same time. For example, use this category to route audio to both a USB device and a set of headphones. Use of this category requires a more detailed knowledge of, and interaction with, the capabilities of the available audio routes.

Discussion

Each app running in iOS has a single audio session, which in turn has a single category. You can change your audio session’s category while your app is running.

You can refine the configuration provided by the AVAudioSessionCategoryPlayback, AVAudioSessionCategoryRecord, and AVAudioSessionCategoryPlayAndRecord categories by using an audio session mode, as described in Audio Session Modes.

If you activate your session while using this option, your app’s audio will not interrupt audio from other apps (such as the Music app). If not using this option (or a category that is implicitly mixable), activating your session will interrupt other nonmixable sessions.

Available in iOS 6.0 and later.

DuckOthers

AVAudioSessionCategoryOptionDuckOthers

Causes audio from other sessions to be ducked (reduced in volume) while audio from this session plays.

Use this option if you want audio from your app (for example, voice prompts in a navigation app) to be heard over music or other currently playing audio. Note that ducking begins when you activate your app’s audio session and ends when you deactivate the session.

Available in iOS 6.0 and later.

AllowBluetooth

AVAudioSessionCategoryOptionAllowBluetooth

Allows Bluetooth handsfree devices to appear as available input routes.

When using this option and no other audio route (such as a headset) is available, session audio will play through the device’s built-in speaker. When not using this option, and no other audio output is available or selected, audio will play through the receiver (a speaker intended to be held to the ear). Note that only iPhone devices are equipped with a receiver; on iPad and iPod touch devices, this option has no effect.

Constants

The default mode; used unless you set a mode with the setMode:error: method.

You can use this mode with every audio session category.

Available in iOS 5.0 and later.

AVAudioSessionModeVoiceChat

AVAudioSessionModeVoiceChat

Specify this mode if your app is performing two-way voice communication, such as using Voice over Internet Protocol (VoIP).

When this mode is in use, the device’s tonal equalization is optimized for voice and the set of allowable audio routes is reduced to only those appropriate for voice chat. For use with the AVAudioSessionCategoryPlayAndRecord audio session category. Apple recommends using the Voice Processing Audio Unit with this mode (see Audio Unit Hosting Guide for iOS).

Discussion

Each app running in iOS has a single audio session, which in turn has a single mode. A mode refines the device’s audio configuration according to the purpose of the mode. Change your audio session’s mode only if your audio session category is configured to disallow mixing with other apps (see AVAudioSessionCategoryOptionMixWithOthers); mode applies to the system as a whole, so an app whose session is active and nonmixable will typically typically control the mode for the system.

Note

Misusing a mode by setting it for an inappropriate audio session category—such as setting the AVAudioSessionModeGameChat mode for the AVAudioSessionCategoryMultiRoute category—results in the behavior provided by the AVAudioSessionModeDefault mode.

Constants

OptionNotifyOthersOnDeactivation

AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation

When passed in the flags parameter of the setActive:withOptions:error: instance method, indicates that when your audio session deactivates, other audio sessions that had been interrupted by your session can return to their active state.

This flag is used only when deactivating your audio session; that is, when you pass a value of NOfalse in the beActive parameter of the setActive:withOptions:error: instance method.

Declaration

Constants

AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation

AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation

When passed in the flags parameter of the setActive:withFlags:error: instance method, indicates that when your audio session deactivates, other audio sessions that had been interrupted by your session can return to their active state.

Availability

Use this notification as a cue to take any appropriate steps to handle requests that come in before the server restarts. Most applications need not subscribe to this notification and should subscribe to the AVAudioSessionMediaServicesWereResetNotification notification instead.