skip to content

With AVKit, how do you play a remote lesson video in AVPlayerViewController, and which AVAudioSession category keeps its sound on in silent mode?

level: juniorimportance: must knowfreq 72%

answer

  1. a player object, a controller object
  2. assign, present, then play
  3. default category obeys the Silent switch
  4. the category for central media playback
  5. background mode for audio and PiP

basics

~20 s

Create an AVPlayer from the URL, assign it to an AVPlayerViewController's player property, present the controller and call play(). Set the AVAudioSession category to .playback first; the default soloAmbient category is silenced by the Silent switch.

solid answer

~40 s

AVKit's `AVPlayerViewController` is only the system UI; the playback engine is an `AVPlayer`. I create `AVPlayer(url:)` with the lesson's URL, set it as the controller's `player`, present the controller and call `play()` on the player, usually in the presentation's completion. Before that I set `AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)`: the default category, `soloAmbient`, is silenced by the Ring/Silent switch and by screen lock, while `.playback` keeps the lesson audible. If the video should keep playing after the user leaves the app, including in Picture in Picture, the target also needs the Audio, AirPlay, and Picture in Picture background mode. `AVPlayerViewController` already supplies the transport controls, AirPlay and PiP, and it is not meant to be subclassed.

code

swift · 18 lines
swift
import AVKit
import UIKit

@MainActor
func playLesson(from presenter: UIViewController, url: URL) {
    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)
    } catch {
        print("Could not set the playback category: \(error)")
    }
    let player = AVPlayer(url: url)
    let controller = AVPlayerViewController()
    controller.player = player
    controller.allowsPictureInPicturePlayback = true
    presenter.present(controller, animated: true) {
        player.play()
    }
}

go deeper

for a junior

Recall the split: AVPlayer plays, AVPlayerViewController shows the system controls, and the .playback category keeps sound on with the Silent switch set to silent.

for a middle

Explain why soloAmbient is the default and what it does, when to activate the session, and which background mode PiP and background audio need.

for a senior

Show how you would diagnose a silent or stopped lesson in production: the category, the background mode, a failed AVPlayerItem status and its error.

for a principal

Argue for the system player as the team default: it inherits each release's controls, AirPlay and PiP, and custom players should need a written reason.

## Three objects, three jobs Playing a lesson video on iOS touches three frameworks, and each owns one part of the job: - **`AVPlayer`** (AVFoundation) is the playback engine. It loads media from a URL, decodes it, keeps time and exposes `play()`, `pause()`, `rate` and `timeControlStatus`. - **`AVPlayerViewController`** (AVKit) is a view controller that draws the video and the **system playback controls**: scrubber, play and pause, AirPlay, Picture in Picture, subtitles and speed options. It shows whatever `AVPlayer` you assign to its `player` property. - **`AVAudioSession`** (AVFAudio) is the app-wide object that tells iOS what kind of audio the app makes, and therefore how the system treats it. A beginner's most common confusion is to expect the view controller to play by itself. It does not own a URL; it presents a player you give it. ## Presenting and starting playback The sequence is short: 1. Configure the audio session category (see below). 2. Create `AVPlayer(url:)` with the remote lesson URL. This wraps the URL in an `AVPlayerItem` for you. 3. Create an `AVPlayerViewController` and set its `player`. 4. Present it modally (or embed it as a child view controller) and call `player.play()`, typically in the presentation's completion block. Apple's documentation states that **`AVPlayerViewController` does not support subclassing**. To add your own badge or watermark between the video and the controls you use its `contentOverlayView`; to hide the system controls entirely you set `showsPlaybackControls` to `false`, and you then own every control yourself. Because the controller adopts the styling and features of each new iOS release automatically, it is the default choice for showing a finished video to a user. ## Why the audio session category matters Every app starts with an audio session in the **`soloAmbient`** category. Its documented behaviour: playback silences other background audio, and the app's audio is **silenced by the Ring/Silent switch and by screen lock**. That is right for a game's sound effects and wrong for a lesson video, where sound is the point. | Category | Silent switch | Mixes with other audio | Typical use | |---|---|---|---| | `soloAmbient` (default) | silences the app | no | incidental sounds | | `ambient` | silences the app | yes | play-along sounds over music | | `playback` | keeps playing | no, unless `mixWithOthers` | video and music players | | `playAndRecord` | keeps playing | no, unless `mixWithOthers` | recording plus playback | Setting `.playback`, ideally with the `.moviePlayback` mode for long-form video, tells iOS that media playback is central to the app. Apple recommends **deferring activation** (`setActive(true)`) until playback actually begins, so that merely launching the app does not interrupt music the user is already listening to. ## Background audio and Picture in Picture The category alone does not keep sound going once the app leaves the foreground. For that, the target needs the **Background Modes** capability with **Audio, AirPlay, and Picture in Picture** selected (the `audio` value of `UIBackgroundModes` in Info.plist). Apple's playback guide names that mode as the requirement for background audio, AirPlay streaming and Picture in Picture. With that in place, `AVPlayerViewController` provides PiP itself: - `allowsPictureInPicturePlayback` defaults to `true`. - `canStartPictureInPictureAutomaticallyFromInline` defaults to `false` and applies only to an embedded, inline player; Apple says to set it only for content that is the user's primary focus. - The delegate method `playerViewController(_:restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:)` lets the app bring its lesson screen back when the user taps to leave PiP. You do not create an `AVPictureInPictureController` for this case; that class is for a custom player built on `AVPlayerLayer`. ## Mistakes that show up in review - Using **`AVAudioPlayer`** for a video URL. It plays audio from a file or from data and has no video output. - Leaving the category at the default and then filing a bug that the lesson is mute on some phones, the ones with the switch set to silent. - Adding the background mode but never setting `.playback`, or the reverse, and expecting background playback to work. - Subclassing the controller to restyle it, which Apple does not support. - Activating the session at launch, which stops the user's music before they have asked for the lesson. Knowing these pieces lets a junior engineer ship a correct video screen in a few lines, and explains most reports that a video plays silently.

  • How does the app learn that the remote lesson failed to load?
    Observe the `AVPlayerItem`'s `status` with key-value observing. When it becomes `.failed`, read the item's `error` for the cause. The header says a failed item can no longer be used for playback, so retrying means creating a new `AVPlayerItem` and calling `replaceCurrentItem(with:)` on the player.
  • Why does Apple suggest deferring setActive(true) until playback starts?
    Activating a non-mixable session such as `.playback` interrupts other audio that is playing, for example the user's music. Setting the category early is harmless, but activating at launch would stop that music before the user has asked for the lesson, so activation waits until play is pressed.
  • What does the app add so the lesson keeps playing in Picture in Picture after the user goes home?
    The Background Modes capability with Audio, AirPlay, and Picture in Picture, plus the `.playback` category. `AVPlayerViewController` then offers PiP itself because `allowsPictureInPicturePlayback` defaults to `true`; no separate PiP controller is created for the system player.

  • AVAudioPlayer can play the lesson video from its remote URL
  • The default audio session category already plays through the Silent switch
  • Setting .playback alone keeps the lesson playing in the background
  • Subclass AVPlayerViewController to restyle its controls
  • AVPlayerViewController needs its own AVPictureInPictureController for PiP