Class

AVAudioSession

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

Declaration

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

Topics

Getting the Audio Session

class func sharedInstance() -> AVAudioSession

Returns the shared audio session instance.

Configuring the Audio Session

var category: AVAudioSession.Category

The current audio session category.

func setCategory(AVAudioSession.Category)

Sets the audio session’s category.

var availableCategories: [AVAudioSession.Category]

The audio session categories available on the current device.

struct AVAudioSession.Category

Audio session category identifiers.

var categoryOptions: AVAudioSession.CategoryOptions

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

func setCategory(AVAudioSession.Category, options: AVAudioSession.CategoryOptions)

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

struct AVAudioSession.CategoryOptions

Constants that specify optional audio behaviors.

var mode: AVAudioSession.Mode

The current audio session’s mode.

func setMode(AVAudioSession.Mode)

Sets the audio session’s mode.

var availableModes: [AVAudioSession.Mode]

The audio session modes available on the device.

struct AVAudioSession.Mode

Audio session mode identifiers.

enum AVAudioSession.RouteSharingPolicy

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

Activating the Audio Session

func setActive(Bool, options: AVAudioSession.SetActiveOptions)

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

Requesting Permission to Record

var recordPermission: AVAudioSession.RecordPermission

The current recording permission status.

func requestRecordPermission(PermissionBlock)

Requests the user’s permission to record audio.

Mixing with Other Audio

var isOtherAudioPlaying: Bool

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

var secondaryAudioShouldBeSilencedHint: Bool

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

var allowHapticsAndSystemSoundsDuringRecording: Bool

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

func setAllowHapticsAndSystemSoundsDuringRecording(Bool)

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

var promptStyle: AVAudioSession.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.

enum AVAudioSession.PromptStyle

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.

class let interruptionNotification: NSNotification.Name

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

class let routeChangeNotification: NSNotification.Name

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

class let silenceSecondaryAudioHintNotification: NSNotification.Name

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

class let mediaServicesWereLostNotification: NSNotification.Name

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

class let mediaServicesWereResetNotification: NSNotification.Name

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

Working with Audio Routes

var currentRoute: AVAudioSessionRouteDescription

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

class AVAudioSessionRouteDescription

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

var isInputAvailable: Bool

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

var availableInputs: [AVAudioSessionPortDescription]?

An array of input ports available for audio routing.

var preferredInput: AVAudioSessionPortDescription?

The preferred input port for audio routing.

func setPreferredInput(AVAudioSessionPortDescription?)

Sets the preferred input port for audio routing.

class AVAudioSessionPortDescription

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

var inputDataSource: AVAudioSessionDataSourceDescription?

The currently selected input data source.

var inputDataSources: [AVAudioSessionDataSourceDescription]?

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

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.

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

func overrideOutputAudioPort(AVAudioSession.PortOverride)

Temporarily changes the current audio route.

Working with Audio Channels

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

var inputGain: Float

The gain applied to inputs associated with the session.

var isInputGainSettable: Bool

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

func setInputGain(Float)

Changes the input gain to the specified value.

var outputVolume: Float

The systemwide output volume set by the user.

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 audio input and output.

var inputLatency: TimeInterval

The latency for audio input, in seconds.

var outputLatency: TimeInterval

The latency for audio output, in seconds.

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.

Setting the Aggregated I/O Preference

func setAggregatedIOPreference(AVAudioSession.IOType)

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

Errors

enum AVAudioSession.ErrorCode

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

Relationships

Inherits From

Conforms To