MediaSessionRepresentable
A protocol that provides content metadata, playback state, and commands for a Now Playing session.
Declaration
@MainActor protocol MediaSessionRepresentable : IdentifiableMentioned in
Overview
Conform to this protocol to provide the media content description, playback state, and commands like play(_:), pause(_:), next(_:), previous(_:), and more.
The framework observes your @Observable model and automatically updates the system’s Now Playing interface when your properties change.
The following example shows a basic session representable:
@Observable
class PlayerModel: MediaSessionRepresentable {
let id = "com.example.music"
var currentTrack: Track?
var isPlaying = false
var currentTime: TimeInterval = 0
var content: (any MediaContentRepresentable)? {
guard let track = currentTrack else { return nil }
return MusicContent(
id: track.id,
songTitle: track.title,
artistName: track.artist,
albumName: track.album,
type: .audio,
duration: .finite(track.duration),
isExplicit: track.isExplicit,
artwork: Artwork(id: track.artworkID) { size in
let data = await self.loadArtworkData(with: size)
return try ArtworkRepresentation(data: data)
}
)
}
var playbackSnapshot: MediaPlaybackSnapshot? {
if isPlaying {
return MediaPlaybackSnapshot(state: .playing(rate: 1.0), elapsedTime: currentTime, timestamp: .now)
} else {
return MediaPlaybackSnapshot(state: .paused, elapsedTime: currentTime, timestamp: .now)
}
}
var commands: [MediaCommand] {[
.play { await self.play() },
.pause { await self.pause() },
.next { await self.nextTrack() },
.previous { await self.previousTrack() },
]}
}