I'm trying to create an app that uses the Apple Music API and while I can fetch playlists as I desire when selecting a song from a playlist the music does not play. First I'm getting the playlists, then showing those playlists on a list in a view. Then pass that "song" which is a Track
type into a PlayBackView
. There are several UI components in that view but I want to boil it down here for simplicity's sake to better understand my problem.
struct PlayBackView: View {
@State private var playState: PlayState = .pause
private let player = ApplicationMusicPlayer.shared
@State var song: Track
private var isPlaying: Bool {
return (player.state.playbackStatus == .playing)
}
var body: some View {
VStack {
AsyncImage(url: song.artwork?.url(width: 100, height: 100)) { image in
image
.resizable()
.frame(maxWidth: .infinity)
.aspectRatio(1.0, contentMode: .fit)
} placeholder: {
Image(systemName: "music.note")
.resizable()
.frame(width: 100, height: 100)
}
// Song Title
Text(song.title)
.font(.title)
// Album Title
Text(song.albumTitle ?? "Album Title Not Found")
.font(.caption)
// Play/Pause Button
Button(action: {
handlePlayButton()
}, label: {
Image(systemName: playPauseImage)
})
.padding()
.foregroundStyle(.white)
.font(.largeTitle)
Image(systemName: airplayImage)
.font(ifDeviceIsConnected ? .largeTitle : .title3)
}
.padding()
}
private func handlePlayButton() {
Task {
if isPlaying {
player.pause()
playState = .play
} else {
playState = .pause
await playTrack(song: song)
}
}
}
@MainActor
public func playTrack(song: Track) async {
do {
try await player.play()
playState = .play
} catch {
print(error.localizedDescription)
}
}
}
These are the errors I'm seeing printing in the console in Xcode
prepareToPlay failed [no target descriptor]
The operation couldn’t be completed. (MPMusicPlayerControllerErrorDomain error 1.)
ASYNC-WATCHDOG-1: Attempting to wake up the remote process
ASYNC-WATCHDOG-2: Tearing down connection
Hello @JB184351. Please make sure that:
- You are adding the MusicKit app service to your bundle ID;
- You are including the
NSAppleMusicUsageDescription
along with a usage description in your Info.plist file; - You are authorizing MusicKit:
if await MusicAuthorization.request() == .authorized {
let request = MusicLibraryRequest<Track>()
let response = try await request.response()
song = response.items.first
}
- You are adding songs to your queue:
player.queue = [song]
try await player.play()
playState = .play
Following the above steps, your code worked on my end without issues. Please follow these steps on your end, as well. If the problem persists, then please use Feedback Assistant to submit a bug report, and please reply with your bug report's ID.