Article

Playing Audio from a Video Asset in the Background

Continue playing audio from a video asset when the video moves into the background.

Overview

A common feature of many media playback apps is to continue playing audio when the app is sent to the background. This may be the result of a user switching apps or locking the device. To enable your app to play background audio, you begin by configuring your app’s capabilities and audio session, as described in AVAudioSession and Enabling Background Audio.

Connect or Disconnect the Video Player

If you’re playing audio-only assets, such as MP3 or M4A files, your setup is complete and your app can play background audio. If you need to play the audio portion of a video asset, an additional step is required. If the player’s current item is displaying video on the device, playback of the AVPlayer instance is automatically paused when the app is sent to the background. If you want to continue playing audio, you disconnect the AVPlayer instance from the presentation when entering the background and reconnect it when returning to the foreground.

func applicationDidEnterBackground(_ application: UIApplication) {

    // Disconnect the AVPlayer from the presentation when entering background

    // If presenting video with AVPlayerViewController
    playerViewController.player = nil

    // If presenting video with AVPlayerLayer
    playerLayer.player = nil
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Reconnect the AVPlayer to the presentation when returning to foreground

    // If presenting video with AVPlayerViewController
    playerViewController.player = player

    // If presenting video with AVPlayerLayer
    playerLayer.player = player
}

See Also

Working with Background Audio

Enabling Background Audio

Configure your app to continue playing audio when it goes into the background.

Controlling Background Audio

Support controlling background audio from the Control Center and iOS Lock screen.