Class

AVAudioSession

An 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 general nature of your app’s audio without detailing the specific behavior or required interactions with the audio hardware. You delegate 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, tvOS, and watchOS apps have a default audio session that comes preconfigured with the following behavior:

  • It supports audio playback, but disallows audio recording (tvOS doesn’t support audio recording).

  • In iOS, setting the Ring/Silent switch to silent mode silences any audio the app is playing.

  • In iOS, locking a device silences the app’s audio.

  • When the app plays audio, it silences any other background audio.

Although the default audio session provides useful behavior, it generally doesn’t provide the audio behavior a media app needs. 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 AVAudioSessionCategoryPlayback is the one that playback apps most commonly use. 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). Using this category, you 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. This class is a singleton object used to set the audio session’s category, mode, and 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: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    // Get the singleton instance.
    let audioSession = AVAudioSession.sharedInstance()
    do {
        // Set the audio session category, mode, and options.
        try audioSession.setCategory(.playback, mode: .moviePlayback, options: [])
    } catch {
        print("Failed to set audio session category.")
    }
    
    // Other post-launch configuration.
    return true
}

The audio session uses this configuration when you activate the session using the setActive:error: or setActive:withOptions:error: method.

Topics

Getting the Audio Session

+ sharedInstance

Returns the shared audio session instance.

- init

Gets a reference to the singleton audio session.

Deprecated

Configuring the Audio Session

category

The current audio session category.

- setCategory:error:

Sets the audio session’s category.

availableCategories

The audio session categories available on the current device.

AVAudioSessionCategory

Audio session category identifiers.

categoryOptions

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

- setCategory:withOptions:error:

Sets the audio session’s category with the specified options.

AVAudioSessionCategoryOptions

Constants that specify optional audio behaviors.

mode

The current audio session’s mode.

- setMode:error:

Sets the audio session’s mode.

- setCategory:mode:options:error:

Sets the audio session’s category, mode, and options.

availableModes

The audio session modes available on the device.

AVAudioSessionMode

Audio session mode identifiers.

routeSharingPolicy

The current route-sharing policy.

- setCategory:mode:routeSharingPolicy:options:error:

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

AVAudioSessionRouteSharingPolicy

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

Activating the Audio Session

- 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:

Activates an audio session asynchronously on watchOS.

- setActive:withFlags:error:

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

Deprecated

Requesting Permission to Record

recordPermission

The current recording permission status.

- requestRecordPermission:

Requests the user’s permission to record audio.

Mixing with Other Audio

otherAudioPlaying

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

secondaryAudioShouldBeSilencedHint

A Boolean value that indicates whether another app, with a nonmixable audio session, is playing audio.

allowHapticsAndSystemSoundsDuringRecording

A Boolean value that indicates whether system sounds and haptics play while recording from audio input.

- setAllowHapticsAndSystemSoundsDuringRecording:error:

Sets a Boolean value that indicates whether system sounds and haptics play while recording from audio input.

promptStyle

A hint to audio sessions that use voice prompt mode to alter the type of prompts they issue in response to other system audio, such as Siri and phone calls.

AVAudioSessionPromptStyle

Constants that indicate the prompt style to use.

Responding to Audio Session Notifications

Responding to Audio Session Interruptions

Observe audio session notifications to ensure that your app responds appropriately to interruptions.

Responding to Audio Session Route Changes

Observe audio session notifications to ensure that your app responds appropriately to route changes.

AVAudioSessionInterruptionNotification

A notification that’s posted when an audio interruption occurs.

Interruption Flags

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

AVAudioSessionRouteChangeNotification

A notification that’s posted when the system’s audio route changes.

AVAudioSessionSilenceSecondaryAudioHintNotification

A notification that’s posted when the primary audio from other applications starts and stops.

AVAudioSessionMediaServicesWereLostNotification

A notification that’s posted when the system terminates the media server.

AVAudioSessionMediaServicesWereResetNotification

A notification that’s posted when the media server restarts.

Working with Audio Routes

currentRoute

A description of the current audio route’s input and output ports.

AVAudioSessionRouteDescription

An object that describes the input and output ports associated with a session’s audio route.

inputAvailable

A Boolean value that indicates whether an audio input path is available.

availableInputs

An array of input ports available for audio routing.

preferredInput

The preferred input port for audio routing.

- setPreferredInput:error:

Sets the preferred input port for audio routing.

AVAudioSessionPortDescription

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

inputDataSource

The currently selected input data source.

inputDataSources

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

- 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.

AVAudioSessionDataSourceDescription

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

- overrideOutputAudioPort:error:

Temporarily changes the current audio route.

inputIsAvailable

A Boolean value that indicates whether a hardware audio input path is available.

Deprecated

Working with Audio Channels

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.

currentHardwareInputNumberOfChannels

The number of audio hardware input channels.

Deprecated
currentHardwareOutputNumberOfChannels

The number of audio hardware output channels.

Deprecated

Working with Audio Device Settings

inputGain

The gain applied to inputs associated with the session.

inputGainSettable

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

- setInputGain:error:

Changes the input gain to the specified value.

outputVolume

The systemwide output volume set by the user.

sampleRate

The current audio sample rate, in hertz.

preferredSampleRate

The preferred sample rate, in hertz.

- setPreferredSampleRate:error:

Sets the preferred sample rate for audio input and output.

inputLatency

The latency for audio input, in seconds.

outputLatency

The latency for audio output, in seconds.

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.

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

Setting the Aggregated I/O Preference

- setAggregatedIOPreference:error:

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

Errors

AVAudioSessionErrorCode

Codes that describe error conditions that may occur when performing audio session operations.

Deprecated

delegate

The delegate object for the audio session.

Deprecated
AVAudioSessionDelegate

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

Deprecated

Relationships

Inherits From