A couple of weeks ago I got help here to play one song and the solution to my problem was that I wasn't adding the song (Track Type) to the queue correctly, so now I want to be able to add a playlist worth of songs to the queue. The problem is when I try to add an array of the Track
type I get an error. The other part of this issue for me is how do I access an individual song off of the queue after I add it? I see I can do ApplicationMusicPlayer.shared.queue.currentItem
but I think I'm missing/misunderstanding something here. Anyway's I'll post the code I have to show how I'm attempting to do this at this moment.
In this scenario we're getting passed in a playlist from another view.
import SwiftUI
import MusicKit
struct PlayBackView: View {
@State var song: Track?
@State private var songs: [Track] = []
@State var playlist: Playlist
private let player = ApplicationMusicPlayer.shared
VStack {
// Album Cover
HStack(spacing: 20) {
if let artwork = player.queue.currentEntry?.artwork {
ArtworkImage(artwork, height: 100)
} else {
Image(systemName: "music.note")
.resizable()
.frame(width: 100, height: 100)
}
VStack(alignment: .leading) {
// Song Title
Text(player.queue.currentEntry?.title ?? "Song Title Not Found")
.font(.title)
.fixedSize(horizontal: false, vertical: true)
}
}
}
.padding()
.task {
await loadTracks()
// It's Here I thought I could do something like this
player.queue = tracks
// Since I can do this with one singular track
player.queue = [song]
do {
try await player.queue.insert(songs, position: .afterCurrentEntry)
} catch {
print(error.localizedDescription)
}
}
}
@MainActor
private func loadTracks() async {
do {
let detailedPlaylist = try await playlist.with([.tracks])
let tracks = detailedPlaylist.tracks ?? []
setTracks(tracks)
} catch {
print(error.localizedDescription)
}
}
@MainActor
private func setTracks(_ tracks: MusicItemCollection<Track>) {
songs = Array(tracks)
}
}