Member-only story
Don’t Stop the Music in Your iOS App
Keeping your AVAudioSession active when entering the background

There are many ways of playing audio files in an iOS app, ranging from SpriteKit
’s SKAction
emitting audio in a game to using the AudioToolbox
framework. In this example, we will use AVAudioPlayer
from the frameworkAVKit
, since it is the most common and easiest to set up and use.
However, without additional preparation, the music will stop playing once the app enters the background or the device gets locked. In this tutorial, we will look at how to keep it playing.
Project Setup
The first step is to enable audio in background mode. This can be done by adding the capability Background Modes in the project settings under the tab Signing & Capabilities.

Once the capability is added, we need to check the box Audio, AirPlay, and Picture in Picture.

Now everything is set up we can dive into some code!
Playing Audio
We can create a new AVAudioPlayer
by providing it with a URL to the file we want to play. Additionally, we can set some properties, e.g. numberOfLoops
. By setting this value to a negative number, the player will repeat its audio in an endless loop.
let url = Bundle.main.url(forResource: "sound", withExtension: "mp3")!
try player = AVAudioPlayer.init(contentsOf: url)
player.numberOfLoops = -1
We could start using the player right now by calling its play()
method, but it would stop once the app is closed. Note: You need to test this on a real device, the simulator will actually keep your sound playing.
In order to change this, there are two things we need to do:
- Configure the system-wide
AVAudioSession
. - Activate our app’s audio session.