Class

AVAudioSession

An intermediary object that communicates to the system how you intend to use audio in your app.

Declaration

@interface AVAudioSession : NSObject

Overview

An audio session acts as an intermediary between your app and the operating system—and, in turn, the underlying audio hardware. You use an audio session to communicate to the operating system the nature of your app’s audio without detailing the specific behavior or required interactions with the audio hardware. This behavior delegates the management of those details to the audio session, which ensures that the operating system can best manage the user’s audio experience.

All iOS and tvOS apps have a default audio session that comes preconfigured as follows:

  • Audio playback is supported, but audio recording is disallowed (audio recording isn't supported in tvOS).

  • In iOS, setting the Ring/Silent switch to silent mode silences any audio being played by the app.

  • In iOS, when the device is locked, the app's audio is silenced.

  • When the app plays audio, any other background audio is silenced.

Although the default audio session provides useful behavior, it doesn't provide the general audio behavior you need when building a media playback app. To change the default behavior, you configure your app’s audio session category.

There are seven possible categories you can use (see Audio Session Categories and Modes), but the one most playback apps need is called AVAudioSessionCategoryPlayback. This category indicates that audio playback is a central feature of your app. When you specify this category, your app’s audio continues with the Ring/Silent switch set to silent mode (iOS only). With this category, your app can also play background audio if you're using the Audio, AirPlay, and Picture in Picture background mode. For more information, see Enabling Background Audio.

You use an AVAudioSession object to configure your app’s audio session. AVAudioSession is a singleton object used to set the audio session category and perform other configurations. You can interact with the audio session throughout your app’s life cycle, but it’s often useful to perform this configuration at app launch, as shown in the following example.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool {
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryPlayback)
    } catch {
        print("Setting category to AVAudioSessionCategoryPlayback failed.")
    }
    // Other project setup
    return true
}

This category is used when you activate the audio session using the setActive:error: or setActive:withOptions:error: method.

Topics

First Steps

Access your app's singleton audio session instance to configure its category, mode, and preferred device settings.

+ sharedInstance

Returns the shared audio session instance.

Configuring the Audio Session

Configure your app’s audio session by setting its category, options, and mode.

category

The current audio session category.

- setCategory:error:

Sets the current audio session category.

- setCategory:withOptions:error:

Sets the audio session category with the specified options.

- setCategory:mode:options:error:

Sets the audio session category, mode, and desired options.

availableCategories

The audio session categories available on the current device.

categoryOptions

The mask of options associated with the current audio session category.

mode

The current audio session mode.

- setMode:error:

Sets the audio session mode.

availableModes

The audio session modes available on the device.

Activating the Audio Session

Activate your audio session with its category and mode configuration.

- setActive:error:

Activates or deactivates your app’s audio session.

- setActive:withOptions:error:

Activates or deactivates your app’s audio session using the specified options.

- activateWithOptions:completionHandler:

Asynchronously activates an audio session on watchOS.

Requesting Permission to Record

Request explicit permission from the user to record audio.

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. You can explicitly ask earlier by calling the requestRecordPermission: method. Until the user grants your app permission to record, your app can record only silence.

recordPermission

Returns the current recording permission status.

- requestRecordPermission:

Requests the user’s permission for audio recording.

Responding to Other Audio

Determine if other apps are playing background audio so you can decide how, or if, to play audio in your app.

otherAudioPlaying

A Boolean value indicating whether another app is currently playing audio.

secondaryAudioShouldBeSilencedHint

A Boolean value that indicates whether another application is playing audio.

Responding to Audio Session Notifications

Register to listen for state change notifications prior to activating your audio session.

AVAudioSession posts notifications indicating important state changes such as interruptions, route changes, and media services resets. Register to listen for these notifications prior to activating your audio session.

Responding to Audio Session Interruptions

Directly observe audio session notifications to ensure that your app responds to interruptions.

Responding to Audio Session Route Changes

Directly observe audio session notifications to ensure that your app responds to interruptions.

AVAudioSessionInterruptionNotification

Posted when an audio interruption occurs.

AVAudioSessionRouteChangeNotification

Posted when the system’s audio route changes.

AVAudioSessionSilenceSecondaryAudioHintNotification

Posted when the primary audio from other applications starts and stops.

AVAudioSessionMediaServicesWereLostNotification

Posted when the media server is terminated.

AVAudioSessionMediaServicesWereResetNotification

Posted when the media server restarts.

Working with Audio Routes

Inspect the state of device audio routes and configure your preferred input and output route settings.

An audio route is an electronic pathway for audio signals. Inspect the state of device audio routes and configure your preferred input and output route settings.

currentRoute

An object describing the current audio input and output route.

inputAvailable

A Boolean value indicating whether an audio input path is available.

availableInputs

An array of input ports available for routing.

preferredInput

The preferred input port for audio routing.

- setPreferredInput:error:

Sets the preferred input port for audio routing.

inputDataSources

An array of available data sources for the audio session’s current input port.

inputDataSource

The currently selected input data source.

- setInputDataSource:error:

Selects a data source for the audio session’s current input port.

outputDataSources

An array of available output data sources for the current audio route.

outputDataSource

The currently selected output data source.

- setOutputDataSource:error:

Sets the output data source for an audio session.

- overrideOutputAudioPort:error:

Temporarily changes the current audio route.

routeSharingPolicy

The current routing policy.

- setCategory:mode:routeSharingPolicy:options:error:

Sets the session category, mode, route sharing policy, and options.

Working with Audio Channels

Inspect and configure the number of audio input and output channels available on the current audio device.

inputNumberOfChannels

The number of audio input channels for the current route.

maximumInputNumberOfChannels

The maximum number of input channels available for the current audio route.

preferredInputNumberOfChannels

The preferred number of input channels for the current route.

- setPreferredInputNumberOfChannels:error:

Sets the preferred number of input channels for the current route.

outputNumberOfChannels

The number of audio output channels.

maximumOutputNumberOfChannels

The maximum number of output channels available for the current audio route.

preferredOutputNumberOfChannels

The preferred number of output channels for the current route.

- setPreferredOutputNumberOfChannels:error:

Sets the preferred number of output channels for the current route.

Working with Audio Device Settings

Inspect and configure audio device settings such as input gain, sample rate, and I/O buffer duration.

Inspect and configure audio device settings such as input gain, sample rate, and I/O buffer duration.

inputGain

The gain applied to inputs associated with the session.

inputGainSettable

A Boolean value that indicates whether the input gain can be set.

- setInputGain:error:

Changes the input gain to the specified value.

outputVolume

The system wide output volume set by the user.

inputLatency

The latency for audio input, measured in seconds.

outputLatency

The latency for audio output, measured in seconds.

sampleRate

The current audio sample rate, in hertz.

preferredSampleRate

The preferred sample rate, in hertz.

- setPreferredSampleRate:error:

Sets the preferred sample rate for input and output.

IOBufferDuration

The current I/O buffer duration, in seconds.

preferredIOBufferDuration

The preferred I/O buffer duration, in seconds.

- setPreferredIOBufferDuration:error:

Sets the preferred audio I/O buffer duration, in seconds.

Setting the Aggregated I/O Preference

Configure your preferred audio input behavior by setting your aggregated I/O preference.

Starting with iOS 10, AVCaptureSession has changed its default audio input configuration on iPhones and iPads that support the Live Photos feature. This change allows taking a Live Photo without interrupting background audio playback. Configure your preferred audio input behavior by setting your aggregated I/O preference.

- setAggregatedIOPreference:error:

Sets the audio session's aggregated I/O configuration preference.

Constants

Audio Session Categories

Category identifiers for audio sessions, used to set the session's category property.

Audio Session Modes

Mode identifiers for audio sessions, used to set the session's mode property.

Audio Session Error Codes

Error codes used in NSError objects returned by AVAudioSession methods.

Interruption Flags

Constants that indicate the state of the audio session following an interruption.

Activation Flags

Flags that provide additional information about your app’s audio intentions upon session activation or deactivation.

AVAudioSessionRouteSharingPolicy

Cases that indicate the possible route-sharing policies for an audio session.

Deprecations

- init

Gets a reference to the singleton audio session.

Deprecated
delegate

The delegate object for the audio session.

Deprecated
inputIsAvailable

A Boolean value that indicates whether a hardware audio input path is available (YES), or not (NO).

Deprecated
- setActive:withFlags:error:

Activates or deactivates your app’s audio session; provides flags for use by other audio sessions.

Deprecated
currentHardwareInputNumberOfChannels

The number of audio hardware input channels.

Deprecated
currentHardwareOutputNumberOfChannels

The number of audio hardware output channels.

Deprecated
currentHardwareSampleRate

The audio hardware sample rate, in hertz.

Deprecated
preferredHardwareSampleRate

The preferred hardware sample rate, in hertz.

Deprecated
- setPreferredHardwareSampleRate:error:

Sets the preferred hardware sample rate for input and output.

Deprecated

Supporting Types

AVAudioSessionDelegate

A protocol that defines responses to changes in state for the audio session.

Deprecated
AVAudioSessionChannelDescription

A channel description provides descriptive information about a hardware channel on the current device.

AVAudioSessionDataSourceDescription

A description that defines a data source for an audio input or output, giving information such as the source’s name, location and orientation.

AVAudioSessionPortDescription

Information about the capabilities of the port and the hardware channels it supports.

AVAudioSessionRouteDescription

A route description manages the input and output ports associated with the current audio route for a session.

Relationships

Inherits From