Class

AVAudioSession

An audio session is a Singleton object that you employ to set the audio context for your app and to express to the system your intentions for your app’s audio behavior.

Overview

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 also handles requests from other apps—some of which have a higher priority than your app’s audio needs, such as handling a phone call. Because of the intermediary role that the media service plays, your app does not directly control certain audio settings; instead, you request preferred values for these settings and then 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.

For example, to set the number of output channels do the following:

  1. Call setPreferredOutputNumberOfChannels(_:) with a proposed number of channels.

  2. If that method returns true, your request was accepted. Otherwise, examine the NSError parameter to find the cause of the error.

    Even if your request was accepted, the number of channels you proposed might not be available, or the change might not take effect immediately.

  3. Examine the value of the outputNumberOfChannels property to see what the current number of channels is, or use Key-value observing to see when it changes.

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 should reapply your preferred audio settings, as needed, when your audio session reactivates. Subscribe to the AVAudioSessionRouteChange notification to respond to these events.

Your requested changes might not take effect immediately. For example, you can use the setPreferredDataSource(_:) 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 audio session’s category (see Audio Session Categories) helps determine audio input and output behaviors when multiple sessions are active. Other active audio sessions can be associated with system services (such as the Music app, turn-by-turn navigation, or a phone call) or with background apps that support audio (see Background Execution).

To control how your audio session interacts with others, use the setCategory(_:) or setCategory(_:with:) method. If you choose an audio session category or option that supports mixing (see Audio Session Categories and AVAudioSessionCategoryOptions), audio from other apps continues when you make your session active.

The system allows only one audio session to control audio routing. If multiple sessions are active, the system chooses which one controls routing based on priority and whether the sessions are mixable.

Activate Your Audio Session Only as Needed

For best customer experience, activate your audio session only as needed and deactivate it when you are not using audio. This is essential if you use a nonmixing audio session category.

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

When a user responds to a recording permission prompt for your app, the system remembers the choice. If the user has denied recording permission, they can reenable it in Settings > Privacy > Microphone.

Media Services Availability

Under certain circumstances, the system terminates and restarts its media services daemon. Respond to these events by reinitializing your app’s audio objects (such as players, recorders, converters, or audio queues) and reasserting preferred audio session settings.

To be notified of media server restart, subscribe to the AVAudioSessionSilenceSecondaryAudioHintType notification.

Symbols

Getting the Shared Audio Session

class func sharedInstance()

Returns the singleton audio session.

Requesting Permission to Record

func requestRecordPermission(PermissionBlock)

Requests the user’s permission for audio recording.

func recordPermission()

The current recording permission status.

Managing an Audio Session

var category: String

The current audio session category.

var availableCategories: [String]

The audio session categories available on the device.

var categoryOptions: AVAudioSessionCategoryOptions

The options associated with the current audio session category.

func setCategory(String)

Sets the current audio session category.

func setCategory(String, with: AVAudioSessionCategoryOptions = [])

Sets the audio session category with the specified options.

var mode: String

The current audio session mode.

var availableModes: [String]

The audio session modes available on the device.

func setMode(String)

Sets the audio session mode.

func setActive(Bool)

Activates or deactivates your app’s audio session.

func setActive(Bool, with: AVAudioSessionSetActiveOptions = [])

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

Working with Audio Device Settings

var outputVolume: Float

The system wide output volume set by the user.

var inputGain: Float

The gain applied to inputs associated with the session.

var isInputGainSettable: Bool

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

func setInputGain(Float)

Changes the input gain to the specified value.

var inputLatency: TimeInterval

The latency for audio input, in seconds.

var outputLatency: TimeInterval

The latency for audio output, measured in seconds.

var sampleRate: Double

The audio sample rate, in hertz, that is currently in effect.

var preferredSampleRate: Double

The preferred sample rate, in hertz.

func setPreferredSampleRate(Double)

Sets the preferred sample rate for input and output.

var ioBufferDuration: TimeInterval

The I/O buffer duration, in seconds, that is currently in effect.

var preferredIOBufferDuration: TimeInterval

The preferred I/O buffer duration, in seconds.

func setPreferredIOBufferDuration(TimeInterval)

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

var secondaryAudioShouldBeSilencedHint: Bool

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

Working with Audio Channels

var inputNumberOfChannels: Int

The number of audio input channels for the current route.

var maximumInputNumberOfChannels: Int

The largest number of input channels available for the current route.

var preferredInputNumberOfChannels: Int

The preferred number of input channels for the current route.

func setPreferredInputNumberOfChannels(Int)

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

var outputNumberOfChannels: Int

The number of audio output channels.

var maximumOutputNumberOfChannels: Int

The largest number of output channels available for the current route.

var preferredOutputNumberOfChannels: Int

The preferred number of output channels for the current route.

func setPreferredOutputNumberOfChannels(Int)

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

Working with Audio Input and Output Routes

var currentRoute: AVAudioSessionRouteDescription

An object describing the current audio input and output route.

var isInputAvailable: Bool

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

var isOtherAudioPlaying: Bool

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

func overrideOutputAudioPort(AVAudioSessionPortOverride)

Temporarily changes the current audio route.

var availableInputs: [AVAudioSessionPortDescription]?

An array of input ports available for routing.

var preferredInput: AVAudioSessionPortDescription?

The preferred input port for audio routing.

func setPreferredInput(AVAudioSessionPortDescription?)

Sets the preferred input port for audio routing.

var inputDataSources: [AVAudioSessionDataSourceDescription]?

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

var inputDataSource: AVAudioSessionDataSourceDescription?

The currently selected input data source.

func setInputDataSource(AVAudioSessionDataSourceDescription?)

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

var outputDataSources: [AVAudioSessionDataSourceDescription]?

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

var outputDataSource: AVAudioSessionDataSourceDescription?

The currently selected output data source.

func setOutputDataSource(AVAudioSessionDataSourceDescription?)

Sets the output data source for an audio session.

Constants

PermissionBlock

The signature for the block executed when the user responds to a system prompt for recording permission.

Audio Session Categories

Category identifiers for audio sessions, used as values for the setCategory(_:) method.

AVAudioSessionCategoryOptions

Constants that specify optional audio behaviors. Each option is valid only with specific audio session categories.

Audio Session Modes

Mode identifiers for audio sessions, used as values for the setMode(_:) method.

AVAudioSessionInterruptionOptions

A constant that indicates the state of the audio session following an interruption.

AVAudioSessionSetActiveOptions

A flag that provides additional information about your app’s audio intentions upon session activation or deactivation.

AVAudioSessionRouteChangeReason

Constants indicating the reason for an audio route change.

AVAudioSessionInterruptionType

Constants that describe the state of the audio interruption.

Notification User Info Keys

Keys available in the user info dictionary of an interruption notification.

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.

AVAudioSessionErrorCode

Error codes used in NSError objects returned by AVAudioSession methods.

Port Types

The values that define port types that refer to either input or output.

AVAudioSessionRecordPermission
AVAudioSessionSilenceSecondaryAudioHintType

These constants are returned by AVAudioSessionSilenceSecondaryAudioHintType to indicate whether optional secondary audio muting should begin or end

Notifications

static let AVAudioSessionInterruption: NSNotification.Name

Posted on the main thread when an audio interruption occurs.

static let AVAudioSessionRouteChange: NSNotification.Name

Posted on the main thread when the system’s audio route changes.

static let AVAudioSessionMediaServicesWereLost: NSNotification.Name

Posted on the main thread when the media server terminates.

static let AVAudioSessionMediaServicesWereReset: NSNotification.Name

Posted on the main thread when the media server restarts.

static let AVAudioSessionSilenceSecondaryAudioHint: NSNotification.Name

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

Relationships

Inherits From

Conforms To