When creating an iOS app that deals with audio, it’s important to configure and handle audio sessions properly. Along with setting up an audio session, there are some extra steps required to properly support Bluetooth audio.
1. Configuring Audio Sessions
By default, audio sessions support audio playback but not audio recording. If your app supports recording audio, you will need to manually configure that.
To do this, you can set the categories and modes, depending on what your app needs to do. You can configure these categories using the following code:
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [.allowBluetooth, .defaultToSpeaker])
Let’s break down what this is doing:
.playAndRecord
category – Allows audio playback and recording..default
mode – The default mode for audio sessions..allowBluetooth
option – Required for the app’s audio session to work properly with Bluetooth devices..defaultToSpeaker
option – If no output device (e.g., a pair of headphones) is connected, the app will default to the device’s speaker.
This configuration is one way to handle an audio session for an iOS app that supports input and output.
2. Activating & Deactivating Audio Sessions
Once you’re done configuring the audio session, you can activate it. Setting the audio session to “active” tells the operating system that your app is going to control audio output. Once activated, background audio from other apps will stop. This will allow your app to be the sole provider of audio on the device.
try AVAudioSession.sharedInstance().setActive(true)
Because you took control of the audio session, you may need to give control back to apps playing audio in the background.
try AVAudioSession.sharedInstance().setActive(false, options: [.notifyOthersOnDeactivation])
notifyOthersOnDeactivation
alerts other apps that you’re done with the audio session and that they can use it if they want to.
If Some Bluetooth Devices Aren’t Working…
If your app is using AVCaptureSession for recording, be sure to tell that session that you’re going to be configuring the audio session elsewhere. The following line will tell the capture session not to worry about configuring the audio session:
avCaptureSession.automaticallyConfiguresApplicationAudioSession = false
If you don’t include this line, you can have unwanted behavior (e.g., issues recording audio with AirPods). You should add this after a valid category is set up for the audio session and before the inputs for the capture session are configured.
If you’re creating an iOS app that utilizes audio sessions, it’s necessary to let the operating system know how to handle them. Hopefully, this post helps you avoid some pitfalls that I’ve run into, especially when dealing with Bluetooth.