# MusicKit Patterns

Longer examples for the `musickit-audio` skill. Its SKILL.md covers setup,
authorization, subscription checks and the basic player; this file builds on
that.

## SwiftUI integration

### A shared player model

One `@Observable` object on the main actor owns access and subscription state
and drives the player. Views read it from the environment.

```swift
import MusicKit
import Observation

@MainActor
@Observable
final class ListeningSession {
    private(set) var accessGranted = false
    private(set) var catalogPlayable = false
    private var membershipWatcher: Task<Void, Never>?

    func prepare() async {
        accessGranted = await MusicAuthorization.request() == .authorized
        guard accessGranted else { return }

        catalogPlayable = (try? await MusicSubscription.current.canPlayCatalogContent) ?? false

        membershipWatcher = Task { [weak self] in
            let updates = MusicSubscription.subscriptionUpdates
            for await membership in updates {
                self?.catalogPlayable = membership.canPlayCatalogContent
            }
        }
    }

    func play(_ track: Song) async throws {
        guard catalogPlayable else { return }
        let player = ApplicationMusicPlayer.shared
        player.queue = [track]
        try await player.play()
    }

    func playOrPause() async throws {
        let player = ApplicationMusicPlayer.shared
        let isRunning = player.state.playbackStatus == .playing
        if isRunning { player.pause() } else { try await player.play() }
    }

    func next() async throws {
        try await ApplicationMusicPlayer.shared.skipToNextEntry()
    }
}
```

Install it once near the root with `.environment(session)` and call
`prepare()` from a `.task`. The model does not keep the player in a property:
`ApplicationMusicPlayer` is not `Sendable`, and Swift 6 refuses an async call
such as `play()` on one reached through main-actor state. Each method reads
`ApplicationMusicPlayer.shared` into a local instead.

### Mini player bar

`ArtworkImage` renders MusicKit artwork at a requested size.

```swift
struct NowPlayingBar: View {
    @Environment(ListeningSession.self) private var session
    let track: Song

    var body: some View {
        HStack(alignment: .center, spacing: 10) {
            if let cover = track.artwork {
                ArtworkImage(cover, width: 48, height: 48)
                    .clipShape(.rect(cornerRadius: 8))
            }
            VStack(alignment: .leading, spacing: 2) {
                Text(track.title).font(.subheadline.bold())
                Text(track.artistName).foregroundStyle(.secondary).font(.caption)
            }
            Spacer(minLength: 8)
            Button("Play or pause", systemImage: "playpause.fill") {
                Task { try? await session.playOrPause() }
            }
            .labelStyle(.iconOnly)
        }
        .padding(.horizontal)
    }
}
```

### Search screen

Search as the text changes and clear the list when the field is empty.

```swift
struct CatalogFinder: View {
    @State private var phrase = ""
    @State private var hits: MusicItemCollection<Song> = []

    var body: some View {
        List(hits) { song in
            LabeledContent(song.title, value: song.artistName)
        }
        .searchable(text: $phrase, prompt: "Artists, songs, albums")
        .onChange(of: phrase) { _, newPhrase in
            Task { await refresh(for: newPhrase) }
        }
    }

    private func refresh(for text: String) async {
        guard !text.isEmpty else { hits = []; return }
        var search = MusicCatalogSearchRequest(term: text, types: [Song.self])
        search.limit = 25
        hits = (try? await search.response().songs) ?? []
    }
}
```

## Genre and chart browsing

Pass `genre` explicitly, even when you want all genres, so the intent is clear
at the call site.

```swift
func topTracks() async throws -> MusicItemCollection<Song> {
    let wanted: [MusicCatalogChartKind] = [.mostPlayed]
    var charts = MusicCatalogChartsRequest(genre: nil, kinds: wanted, types: [Song.self])
    charts.limit = 50
    let result = try await charts.response()
    guard let chart = result.songCharts.first else { return [] }
    return chart.items
}
```

A simple way to browse by genre is to search with the genre's name:

```swift
func tracks(tagged style: Genre) async throws -> MusicItemCollection<Song> {
    let label = style.name
    let search = MusicCatalogSearchRequest(term: label, types: [Song.self])
    return try await search.response().songs
}
```

## Library management

Writing to the user's library needs two things: authorization, and iCloud Music
Library turned on for the account.

```swift
func canWriteLibrary() async -> Bool {
    if MusicAuthorization.currentStatus != .authorized { return false }
    let membership = try? await MusicSubscription.current
    return membership?.hasCloudLibraryEnabled ?? false
}

func save(_ track: Song) async throws {
    let library = MusicLibrary.shared
    if await canWriteLibrary() { try await library.add(track) }
}

func save(_ record: Album) async throws {
    let library = MusicLibrary.shared
    if await canWriteLibrary() { try await library.add(record) }
}
```

Reading from the library uses `MusicLibraryRequest`:

```swift
func lastListened() async throws -> MusicItemCollection<Song> {
    var query = MusicLibraryRequest<Song>()
    query.sort(by: \.lastPlayedDate, ascending: false)
    query.limit = 20
    return try await query.response().items
}
```

## Playlist access

A library request for playlists sorts only by `lastPlayedDate`,
`libraryAddedDate` or `name`; `Playlist.lastModifiedDate` exists but is not a
sort key.

```swift
func recentPlaylists() async throws -> MusicItemCollection<Playlist> {
    var query = MusicLibraryRequest<Playlist>()
    query.sort(by: \.lastPlayedDate, ascending: false)
    return try await query.response().items
}

func append(_ tracks: [Song], to list: Playlist) async throws {
    guard await canWriteLibrary() else { return }
    for track in tracks {
        _ = try await MusicLibrary.shared.add(track, to: list)
    }
}
```

## Now Playing session

When an app runs more than one audio source at once (for example a
Picture in Picture video next to a music stream), give each its own
`MPNowPlayingSession`. Each session carries its own command center and info
center, and the app says which one should be the system's Now Playing entry.

```swift
import AVFoundation
import MediaPlayer

@MainActor
func makeVideoSession(for videoPlayer: AVPlayer) -> MPNowPlayingSession {
    let clipSession = MPNowPlayingSession(players: [videoPlayer])
    let controls = clipSession.remoteCommandCenter
    controls.playCommand.addTarget { event in
        videoPlayer.play()
        return .success
    }
    clipSession.nowPlayingInfoCenter.nowPlayingInfo = [
        MPMediaItemPropertyTitle: "Match highlights"
    ]
    clipSession.becomeActiveIfPossible { didBecomeActive in
        // didBecomeActive is false if another app currently owns Now Playing.
    }
    return clipSession
}
```

## Background audio configuration

Set up the audio session before playback starts:

```swift
func configureAudioSession() throws {
    let audio = AVAudioSession.sharedInstance()
    try audio.setCategory(.playback, mode: .default)
    try audio.setActive(true)
}
```

Then list `audio` under the `UIBackgroundModes` key in Info.plist (in Xcode:
Signing and Capabilities, Background Modes, "Audio, AirPlay, and Picture in
Picture").

### Interruptions

Calls, alarms and Siri interrupt playback. Pause when it starts; resume only if
the system says so when it ends. The async notification sequence keeps the
handler on the main actor.

```swift
@MainActor
func followInterruptions(for engine: EpisodeEngine) async {
    let feed = NotificationCenter.default.notifications(named: AVAudioSession.interruptionNotification)
    for await note in feed {
        let info = note.userInfo ?? [:]
        guard let kindValue = info[AVAudioSessionInterruptionTypeKey] as? UInt,
              let kind = AVAudioSession.InterruptionType(rawValue: kindValue) else { continue }

        if kind == .began {
            engine.suspend()   // also remember the position
        } else if kind == .ended {
            let flags = AVAudioSession.InterruptionOptions(
                rawValue: info[AVAudioSessionInterruptionOptionKey] as? UInt ?? 0)
            if flags.contains(.shouldResume) { engine.resume() }
        }
    }
}
```

### Route changes

Pulling out headphones should stop the audio instead of moving it to the
speaker. The system reports that as `.oldDeviceUnavailable`.

```swift
@MainActor
func followRouteChanges(for engine: EpisodeEngine) async {
    let feed = NotificationCenter.default.notifications(named: AVAudioSession.routeChangeNotification)
    for await note in feed {
        let reasonValue = note.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt ?? 0
        if AVAudioSession.RouteChangeReason(rawValue: reasonValue) == .oldDeviceUnavailable {
            engine.suspend()
        }
    }
}
```

Start both from a long-lived `.task` or from the engine's own setup.
`EpisodeEngine` stands for whatever `@MainActor` type drives the app's custom
audio.
