gpt4 book ai didi

swift - Apple MusicKit 按标识符播放专辑不起作用

转载 作者:行者123 更新时间:2023-12-05 02:35:55 33 4
gpt4 key购买 nike

我创建了一个按钮,它获取所选专辑的商店 ID 并将其放入音乐播放器的队列中,但由于某种原因,它没有播放并返回以下错误:

Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=6

这是按钮的代码(我把播放器变量放在那里是为了这里更容易)

var storeIds: [String] = [ "ID" ]
Button(action: {
let player = MPMusicPlayerController.applicationQueuePlayer
let queue = MPMusicPlayerStoreQueueDescriptor(storeIDs: storeIds)
storeIds = ["\(album.id)".replacingOccurrences(of: "l.", with: "")]

print("ID: ", storeIds) // Example ID: ["Qn4Bnha"]
player.setQueue(with: storeIds)
player.play()
})

此外,我删除了“l”。来自 id,因为每张专辑都以不需要的开头。

最佳答案

如果您尝试播放库中的专辑,那么我也遇到了问题。

据我所知,库歌曲的 MusicItemID 与专辑歌曲不同,播放器无法播放。图书馆相册也是如此。如果我得到图书馆歌曲的 ID 并将另一个请求发送到 - https://api.music.apple.com/v1/me/library/albums/{id}/catalog , 然后将其设置到队列中;它工作正常。

作为解决方法,您可以获取相册的本地 ID,然后向目录发出另一个请求。如果 Apple Music 上有专辑,那应该可以。

这是一个适合我的例子:

do {
/// First request to get the heavy rotation albums
guard let url = URL(string: "https://api.music.apple.com/v1/me/history/heavy-rotation") else { return }

let request = MusicDataRequest(urlRequest: URLRequest(url: url))
let response = try await request.response()

let heavyRotationAlbums = try JSONDecoder().decode(MusicItemCollection<Album>.self, from: response.data)

/// Get the first album
guard let album = heavyRotationAlbums.first else { return }

/// Get the local album ID
let albumID = album.id

/// Another request to get the album from Apple Music Catalog
guard let catalogURL = URL(string: "https://api.music.apple.com/v1/me/library/albums/\(albumID)/catalog") else { return }

let catalogRequest = MusicDataRequest(urlRequest: URLRequest(url: catalogURL))
let catalogResponse = try await catalogRequest.response()

let albums = try JSONDecoder().decode(MusicItemCollection<Album>.self, from: catalogResponse.data)

/// Get the same album, but with the catalog ID
guard let catalogAlbum = albums.first else { return }

/// Encode the parameters
let data = try JSONEncoder().encode(catalogAlbum.playParameters)

/// Decode the parameters to `MPMusicPlayerPlayParameters`
let playParameters = try JSONDecoder().decode(MPMusicPlayerPlayParameters.self, from: data)

// Create the queue
let queue = MPMusicPlayerPlayParametersQueueDescriptor(playParametersQueue: [playParameters])

let player = MPMusicPlayerController.applicationMusicPlayer

/// Set the queue
player.setQueue(with: queue)
try await player.prepareToPlay()

/// Finally, play the album!
player.play()
} catch {
print(error)
}

关于swift - Apple MusicKit 按标识符播放专辑不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70407776/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com