An intermediary object that communicates to the system how you intend to use audio in your app.
SDKs
- iOS 3.0+
- tvOS 9.0+
- watchOS 2.0+
Framework
- AVFoundation
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 AVAudio
. 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 AVAudio
object to configure your app’s audio session. AVAudio
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 set
or set
method.
Note
You can activate the audio session at any time after setting its category, but it’s generally preferable to defer this call until your app begins audio playback. Deferring the call ensures that you won’t prematurely interrupt any other background audio that may be in progress.