Better Programming

Advice for programmers.

Follow publication

Member-only story

Don’t Stop the Music in Your iOS App

David Piper
Better Programming
Published in
3 min readNov 24, 2019

--

Image by sweetlouise from pixabay

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.

Adding the Background Modes capability to our app.

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

Allowing audio to play in background.

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:

  1. Configure the system-wide AVAudioSession.
  2. Activate our app’s audio session.

--

--

David Piper
David Piper

Written by David Piper

Working as an iOS and Android dev.

Write a response