0Pricing
Swift Academy · Lesson

Playing Media with AVPlayer

Stream and play audio and video assets.

Playing Media with AVPlayer is a free Swift Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

AVFoundation for Media

AVFoundation is Apple’s framework for working with time-based audiovisual media—playback, capture, editing, and export.

The core playback class is AVPlayer.

import AVFoundation

AVPlayer and AVPlayerItem

AVPlayer controls playback, while AVPlayerItem represents the media being played and tracks its state. An AVAsset backs the item.

let url = URL(string: "https://example.com/video.mp4")!
let item = AVPlayerItem(url: url)
let player = AVPlayer(playerItem: item)

Starting and Pausing

Control playback with play(), pause(), and seek(to:). Playback begins from the current time.

player.play()
// later
player.pause()

Displaying Video

To show video in UIKit, host an AVPlayerLayer in a view. The layer renders the player’s visual output.

let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = view.bounds
playerLayer.videoGravity = .resizeAspect
view.layer.addSublayer(playerLayer)

Observing Status

An AVPlayerItem reports a status. Observe it to know when the media is readyToPlay or has failed.

let observation = item.observe(\.status) { item, _ in
    if item.status == .readyToPlay {
        player.play()
    }
}

Tracking Time

Use addPeriodicTimeObserver to update a progress UI as playback advances. Times are CMTime values.

let interval = CMTime(seconds: 0.5, preferredTimescale: 600)
player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { time in
    let seconds = time.seconds
    print("at \(seconds)s")
}

CMTime Basics

CMTime stores time as a rational number (value over timescale) for sample-accurate precision. A timescale of 600 cleanly divides common frame rates.

let t = CMTime(seconds: 5, preferredTimescale: 600)
let half = CMTimeMultiplyByFloat64(t, multiplier: 0.5)

Seeking Precisely

seek(to:toleranceBefore:toleranceAfter:) with zero tolerance gives frame-accurate seeking, at the cost of more decoding work.

let target = CMTime(seconds: 30, preferredTimescale: 600)
player.seek(to: target, toleranceBefore: .zero, toleranceAfter: .zero)

Reaching the End

Observe AVPlayerItem.didPlayToEndTimeNotification to detect completion—then loop, dismiss, or show the next item.

NotificationCenter.default.addObserver(
    forName: .AVPlayerItemDidPlayToEndTime,
    object: item, queue: .main) { _ in
    player.seek(to: .zero)
    player.play() // loop
}

Audio Session for Playback

For audio that plays correctly (and continues in the background when configured), set up an AVAudioSession with the right category.

let session = AVAudioSession.sharedInstance()
try? session.setCategory(.playback)
try? session.setActive(true)

AVQueuePlayer for Playlists

AVQueuePlayer subclasses AVPlayer to play a queue of items in sequence—ideal for playlists and continuous video feeds.

let queue = AVQueuePlayer(items: [item1, item2, item3])
queue.play()

Quick Check: AVPlayer

Test your understanding of AVPlayer playback.

Recap: Playing Media with AVPlayer

AVPlayer drives playback of an AVPlayerItem backed by an AVAsset; an AVPlayerLayer renders video. Observe item status, track progress with periodic CMTime observers, seek precisely with zero tolerance, and handle end-of-play notifications.

Configure an AVAudioSession for correct audio, and use AVQueuePlayer for playlists.

Frequently asked questions

Is the “Playing Media with AVPlayer” lesson free?

Yes — the full text of “Playing Media with AVPlayer” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Playing Media with AVPlayer”?

Stream and play audio and video assets. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Playing Media with AVPlayer” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Playing Media with AVPlayer
  2. Recording Audio
  3. AVAsset and Composition
  4. Embedding Players in SwiftUI
← Back to Swift Academy