A music app has one special need: the music must keep playing when the screen turns off or the user opens another app. On iOS this takes three pieces working together. An audio session with the playback category tells the system your app is a music app. The Background Modes capability allows audio to continue. And the Now Playing and remote command APIs show the title on the lock screen and make headphone buttons work.
The player is an @Observable class that owns an AVPlayer, so the SwiftUI view only shows the state and sends commands. The track addresses are placeholders: you must supply audio you have the right to play, such as your own recordings or royalty-free music.
Concepts in this project
- AVPlayer and AVPlayerItem: the player plays one item at a time. Replace the item to change track.
- Audio session:
.playbacklets audio continue with the silent switch on and in the background. - Periodic time observer: reports the position twice a second for the slider.
- Now Playing info: title, artist, duration and position for the lock screen and Control Center.
- Remote commands: play, pause, next and previous from headphones, the lock screen and car systems.
- Slider editing state: while the user drags, show the drag position, and seek only when they let go.
Create the project
- In Xcode choose File > New > Project > iOS > App. Set Interface to SwiftUI, Language to Swift, and Testing System to Swift Testing. Set the minimum deployment to iOS 17, because the code uses @Observable. Name the product MusicPlayer.
- Select the app target, open Signing & Capabilities, add Background Modes and tick Audio, AirPlay, and Picture in Picture.
- Open Track.swift and replace the placeholder addresses with audio you have the right to play.
- Delete the default ContentView.swift and the default @main file, then add the files below.
MusicPlayer/
MusicApp.swift @main
Track.swift tracks and time format
AudioPlayer.swift AVPlayer, session, remote commands
PlayerView.swift artwork, slider, buttons
MusicPlayerTests/
MusicTests.swift
The code
`Track.swift`
import Foundation
struct Track: Identifiable, Equatable {
let id = UUID()
let title: String
let artist: String
let url: URL
}
// These addresses are placeholders. Replace them with audio you have the right to play,
// such as your own files or royalty-free music, or the app will show an error.
enum SampleTracks {
static let all: [Track] = [
Track(title: "Morning Light", artist: "Sample Artist",
url: URL(string: "https://example.com/audio/morning-light.mp3")!),
Track(title: "Evening Walk", artist: "Sample Artist",
url: URL(string: "https://example.com/audio/evening-walk.mp3")!),
Track(title: "Rain Window", artist: "Sample Artist",
url: URL(string: "https://example.com/audio/rain-window.mp3")!)
]
}
enum TimeFormat {
// 125 -> "2:05"
static func clock(_ seconds: Double) -> String {
guard seconds.isFinite, seconds >= 0 else { return "0:00" }
let total = Int(seconds)
return "\(total / 60):\(String(format: "%02d", total % 60))"
}
}
`AudioPlayer.swift`
import AVFoundation
import MediaPlayer
import Observation
@Observable
@MainActor
final class AudioPlayer {
private(set) var tracks: [Track]
private(set) var index = 0
private(set) var isPlaying = false
private(set) var position: Double = 0
private(set) var duration: Double = 0
private(set) var errorMessage: String?
private let player = AVPlayer()
private var timeObserver: Any?
private var endObserver: NSObjectProtocol?
init(tracks: [Track] = SampleTracks.all) {
self.tracks = tracks
configureSession()
configureRemoteCommands()
observeTime()
load(index: 0)
}
var current: Track? {
tracks.indices.contains(index) ? tracks[index] : nil
}
func toggle() {
if isPlaying {
player.pause()
} else {
player.play()
}
isPlaying.toggle()
updateNowPlaying()
}
func next() { load(index: (index + 1) % max(tracks.count, 1), autoplay: isPlaying) }
func previous() { load(index: (index - 1 + tracks.count) % max(tracks.count, 1), autoplay: isPlaying) }
func seek(to seconds: Double) {
player.seek(to: CMTime(seconds: seconds, preferredTimescale: 600))
position = seconds
}
private func load(index newIndex: Int, autoplay: Bool = false) {
guard tracks.indices.contains(newIndex) else { return }
index = newIndex
errorMessage = nil
position = 0
duration = 0
let item = AVPlayerItem(url: tracks[newIndex].url)
player.replaceCurrentItem(with: item)
if let endObserver { NotificationCenter.default.removeObserver(endObserver) }
endObserver = NotificationCenter.default.addObserver(
forName: .AVPlayerItemDidPlayToEndTime, object: item, queue: .main
) { [weak self] _ in
Task { @MainActor in self?.next() }
}
Task {
do {
let seconds = try await item.asset.load(.duration).seconds
duration = seconds.isFinite ? seconds : 0
updateNowPlaying()
} catch {
errorMessage = "This track cannot be played right now."
isPlaying = false
}
}
if autoplay { player.play() }
}
private func observeTime() {
let interval = CMTime(seconds: 0.5, preferredTimescale: 600)
timeObserver = player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] time in
Task { @MainActor in
guard let self, time.seconds.isFinite else { return }
self.position = time.seconds
}
}
}
// Needed so audio keeps playing with the screen off. Also turn on the
// "Audio, AirPlay, and Picture in Picture" background mode in Signing & Capabilities.
private func configureSession() {
try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try? AVAudioSession.sharedInstance().setActive(true)
}
private func configureRemoteCommands() {
let center = MPRemoteCommandCenter.shared()
center.playCommand.addTarget { [weak self] _ in
Task { @MainActor in if self?.isPlaying == false { self?.toggle() } }
return .success
}
center.pauseCommand.addTarget { [weak self] _ in
Task { @MainActor in if self?.isPlaying == true { self?.toggle() } }
return .success
}
center.nextTrackCommand.addTarget { [weak self] _ in
Task { @MainActor in self?.next() }
return .success
}
center.previousTrackCommand.addTarget { [weak self] _ in
Task { @MainActor in self?.previous() }
return .success
}
}
private func updateNowPlaying() {
guard let track = current else { return }
MPNowPlayingInfoCenter.default().nowPlayingInfo = [
MPMediaItemPropertyTitle: track.title,
MPMediaItemPropertyArtist: track.artist,
MPMediaItemPropertyPlaybackDuration: duration,
MPNowPlayingInfoPropertyElapsedPlaybackTime: position,
MPNowPlayingInfoPropertyPlaybackRate: isPlaying ? 1.0 : 0.0
]
}
}
`PlayerView.swift`
import SwiftUI
struct PlayerView: View {
@State private var player = AudioPlayer()
@State private var dragPosition: Double?
var body: some View {
VStack(spacing: 24) {
Spacer()
Image(systemName: "music.note")
.font(.system(size: 80))
.frame(width: 220, height: 220)
.background(Color.blue.opacity(0.15), in: RoundedRectangle(cornerRadius: 24))
VStack(spacing: 4) {
Text(player.current?.title ?? "No track").font(.title2.bold())
Text(player.current?.artist ?? "").foregroundStyle(.secondary)
}
if let message = player.errorMessage {
Text(message).foregroundStyle(.red)
}
VStack {
Slider(
value: Binding(
get: { dragPosition ?? player.position },
set: { dragPosition = $0 }
),
in: 0...max(player.duration, 1)
) { editing in
if !editing, let target = dragPosition {
player.seek(to: target)
dragPosition = nil
}
}
HStack {
Text(TimeFormat.clock(dragPosition ?? player.position))
Spacer()
Text(TimeFormat.clock(player.duration))
}
.font(.caption.monospacedDigit())
.foregroundStyle(.secondary)
}
HStack(spacing: 40) {
Button { player.previous() } label: { Image(systemName: "backward.fill") }
.accessibilityLabel("Previous track")
Button { player.toggle() } label: {
Image(systemName: player.isPlaying ? "pause.circle.fill" : "play.circle.fill")
.font(.system(size: 64))
}
.accessibilityLabel(player.isPlaying ? "Pause" : "Play")
Button { player.next() } label: { Image(systemName: "forward.fill") }
.accessibilityLabel("Next track")
}
.font(.title)
Spacer()
}
.padding()
}
}
`MusicApp.swift`
import SwiftUI
@main
struct MusicApp: App {
var body: some Scene {
WindowGroup {
PlayerView()
}
}
}
`MusicTests.swift (in the tests target)`
import Testing
@testable import MusicPlayer
struct MusicTests {
@Test func clockFormat() {
#expect(TimeFormat.clock(0) == "0:00")
#expect(TimeFormat.clock(125) == "2:05")
#expect(TimeFormat.clock(3599) == "59:59")
}
@Test func badValuesAreSafe() {
#expect(TimeFormat.clock(-5) == "0:00")
#expect(TimeFormat.clock(.nan) == "0:00")
#expect(TimeFormat.clock(.infinity) == "0:00")
}
@Test func sampleListIsNotEmpty() {
#expect(!SampleTracks.all.isEmpty)
}
}
Walkthrough
AudioPlayer is created once by the view. Its initialiser sets up the audio session, registers the remote commands, starts the time observer and loads the first track. Everything about playback is in this one class, which keeps the view short.
load(index:) creates an AVPlayerItem and gives it to the player. It also registers for the notification that the item has finished, so the next track starts automatically. The duration is read with await item.asset.load(.duration), which is the modern asynchronous way. If loading fails, the player shows "This track cannot be played right now." That is exactly what you will see until you replace the placeholder addresses.
The periodic time observer runs on the main queue every half second and stores the current position. The slider is bound to that position, but while the user is dragging, the view shows a separate dragPosition value. Only when dragging ends does it call seek. Without this, the slider would jump back to the playing position under the user's finger.
configureRemoteCommands connects the system's buttons to your methods. Each handler returns .success, and uses a Task on the main actor because the player is main-actor isolated. updateNowPlaying fills the dictionary that the lock screen reads. Update it when the track, duration or play state changes.
The tests cover the time format, including bad values such as negative numbers, NaN and infinity, which AVFoundation can report while a stream is loading. Playback itself needs real audio and a device, so it is a manual test.
How it works
- The view calls
toggle,next,previousandseekon the player object. - The player changes the AVPlayer and updates its own published state.
- The time observer feeds the slider and the Now Playing information.
- With Background Modes on, audio keeps playing when you lock the phone, and the lock screen shows controls.
Expected output
With your own audio addresses: the screen shows the first title and artist, a slider, the times 0:00 and the track length, and Previous, Play and Next buttons. Press Play: sound starts and the slider moves. Lock the phone: the music continues and the lock screen shows the title with play and pause. Press Next on the headphones or the lock screen: the track changes. With the placeholder addresses, you see "This track cannot be played right now." and nothing plays. The three tests pass.
Your task
- Replace the track addresses and test background playback on a real iPhone.
- Add shuffle and repeat buttons.
- Show album art with MPMediaItemArtwork.
- Handle interruptions such as phone calls with AVAudioSession.interruptionNotification.
How to check it worked
- Audio continues when the screen locks.
- Lock screen buttons control the app.
- You only play audio you have the right to use.
Next, try the same idea on another platform with the Android Development with Kotlin course, or go deeper on iOS with the Advanced iOS Development course.