Class

AVAudioSession

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

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 playback. 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(_:) or setActive(_:options:) method.

Topics

First Steps

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

class func sharedInstance() -> AVAudioSession

Returns the shared audio session instance.

Configuring the Audio Session

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

var category: AVAudioSession.Category

The current audio session category.

var availableCategories: [AVAudioSession.Category]

The audio session categories available on the current device.

var categoryOptions: AVAudioSession.CategoryOptions

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

var mode: AVAudioSession.Mode

The current audio session mode.

func setMode(AVAudioSession.Mode)

Sets the audio session mode.

var availableModes: [AVAudioSession.Mode]

The audio session modes available on the device.

Activating the Audio Session

Activate your audio session with its category and mode configuration.

func setActive(Bool, options: AVAudioSession.SetActiveOptions = [])

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

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.

var recordPermission: AVAudioSession.RecordPermission

Returns the current recording permission status.

func requestRecordPermission(PermissionBlock)

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.

var isOtherAudioPlaying: Bool

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

var secondaryAudioShouldBeSilencedHint: Bool

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.

class let interruptionNotification: NSNotification.Name

Posted when an audio interruption occurs.

class let routeChangeNotification: NSNotification.Name

Posted when the system’s audio route changes.

class let silenceSecondaryAudioHintNotification: NSNotification.Name

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

class let mediaServicesWereLostNotification: NSNotification.Name

Posted when the media server is terminated.

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.

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

func overrideOutputAudioPort(AVAudioSession.PortOverride)

Temporarily changes the current audio route.

Working with Audio Channels

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

var inputNumberOfChannels: Int

The number of audio input channels for the current route.

var maximumInputNumberOfChannels: Int

The maximum number of input channels available for the current audio 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 maximum number of output channels available for the current audio 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 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.

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

The system wide output volume set by the user.

var inputLatency: TimeInterval

The latency for audio input, measured in seconds.

var outputLatency: TimeInterval

The latency for audio output, measured in seconds.

var sampleRate: Double

The current audio sample rate, in hertz.

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 current I/O buffer duration, in seconds.

var preferredIOBufferDuration: TimeInterval

The preferred I/O buffer duration, in seconds.

func setPreferredIOBufferDuration(TimeInterval)

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.

func setAggregatedIOPreference(AVAudioSession.IOType)

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.

enum AVAudioSession.RouteSharingPolicy

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

Supporting Types

class AVAudioSessionChannelDescription

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

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

class AVAudioSessionPortDescription

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

class AVAudioSessionRouteDescription

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

Relationships

Inherits From

Conforms To

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software