How To Make Your App Support Background Audio Playback

This tutorial is tested with Swift 5 and Xcode 11.6.

In this quick tutorial, I will show you how to quickly add support for background audio playback.

Audio playback in background comes in handy in many use cases, Audiobooks are one famous case. You can play and listen to the audiobook while still being able to use other apps. Youtube also offer background playback as a premium feature in their iOS app.

To get started, I prepared a starter project, download it here.

Open ViewController.swift and make the following modifications:

// At the top of the file
import AVFoundation  

// Inside the class
// A stored property for the audio player
var audioPlayer: AVAudioPlayer!

@IBAction func onStopButtonClick(_ sender: Any) {
   audioPlayer.stop()
   audioPlayer.currentTime = 0
}
@IBAction func onPlayButtonClick(_ sender: Any) {
   if !audioPlayer.isPlaying{
        audioPlayer.play()
   }
}
override func viewDidLoad() {
 super.viewDidLoad()
 do {
      let path:String! = Bundle.main.path(forResource: "Sample", ofType: "mp3")
      audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
      audioPlayer.prepareToPlay()
      audioPlayer.play()
 } catch let error {
      print("Error \(error.localizedDescription)")
 }
}

Since loading an audio may fail, it’s important to load the file inside a do-catch block.

Build and run the project and make sure the audio track playback starts correctly.

So far, if you press the home button, the app will enter to background state and the audio file playback will stop.

Supporting the background mode..

In order for the app to support audio playback in background, you first need to add the background mode capability to the app.

To do so, select the project from the Project navigator, then select Signing & Capabilities, click on the ‘+’ button at the top left and select Background Modes from the list. Finally check the Audio, AirPlay, and Picture in Picture mode.

Add Audio, AirPlay, and Picture in Picture capability to your app

To finish up, select the ViewController.swift file and add the following code to the viewDidLoad method.

// Activate Audio Playback in Background
do {
    try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
    try AVAudioSession.sharedInstance().setActive(true)
    } 
catch let error {
    print("Error \(error.localizedDescription)")
}

Here you go, build and run the project, enter the app to background state and notice how the audio file playback does not get interrupted :]

You can download the final project here.

See you in next article 😉

Malek
iOS developer with over than 11 years of extensive experience working on several projects with different sized startups and corporates.