swift 如何显示流媒体Apple Music的专辑插图?

zf2sa74q  于 2023-03-11  发布在  Swift
关注(0)|答案(5)|浏览(160)

在我的音乐播放器中使用新的Apple Music API(2016年5月12日发布)iOS 9中(swift,虽然我目前也在熟悉Objective-C),我可以显示流媒体歌曲的信息,但不能显示艺术作品。和StoreKit框架。我已经成功地请求了对AddToCloudMusicLibrary和MusicCatalogPlayback的授权。我成功地展示了我从苹果音乐应用程序下载的歌曲中的苹果音乐艺术作品,以及我个人歌曲收藏中的艺术作品。我见过其他人在这方面有问题,但没有运气...
在我显示默认图像(这对于错误处理来说是必须的)或者从其他服务中获取之前,我想再问一次,除非有人要求我帮助解决这个问题,否则我不会显示这个错误。
我第一次尝试发布代码...这是我在一个叫Authorization的swift文件中的代码。我需要在任何地方引用这个代码,还是应该在AppDelegate文件中引用它?这是我项目中唯一不能100%确定的部分。

import StoreKit
import MediaPlayer
import UIKit

class AppleMusicPlayer: NSObject {

    let applePlayer = MPMusicPlayerController.systemMusicPlayer()

    func playID(productID: String) {
        SKCloudServiceController.requestAuthorization { status in
            let controller = SKCloudServiceController()
            controller.requestCapabilitiesWithCompletionHandler { capabilities, error in
                if capabilities != SKCloudServiceCapability.None {
                    MPMediaLibrary.defaultMediaLibrary().addItemWithProductID(productID) { entities, error in
                        self.appPlayer.setQueueWithStoreIDs([productID])
                        self.appPlayer.shuffleMode = .Songs
                        self.appPlayer.play()
                    }
                }
            }
        }
    }
}
o2g1uqev

o2g1uqev1#

这是Apple Music当前API中的一个bug。正如你提到的,不在用户曲库中但从AM流媒体播放的歌曲将不会返回专辑插图。
你应该在www.example.com上提交一个功能增强bugreport.apple.com(你也可以复制我6个月前的25413082)。
在此期间,您最好的选择是使用iTunes API来检索专辑插图,不幸的是,这不会返回正确的结果100%的时间...

9lowa7mx

9lowa7mx2#

我为此纠结了很长时间。如果这真的是一个bug,我不确定,但是你不能像你想象的那样把UIImageView设置为nowPlayingItem。你必须从Apple Music服务API中提取图像。参见文档。也可以看看苹果提供的here示例项目,以获得完整的理解。此外,here是我如何克服这个问题的完整示例。

func updateUserInterface() {
    if musicPlayerManager.musicPlayerController.playbackState == .playing { //Check if anything is playing
        if let currentItem = musicPlayerManager.musicPlayerController.nowPlayingItem {
            songAlbumLabel.text = currentItem.albumTitle
            songTitleLabel.text = currentItem.title
            songArtistNameLabel.text = currentItem.artist
            let albumTitle = currentItem.albumTitle  //Changes here!
            let artist = currentItem.artist  //Changes here!
            if let artwork = musicPlayerManager.musicPlayerController.nowPlayingItem?.artwork, let image = artwork.image(at: artworkImageView.frame.size) { // Check for local image
                print("using local image")
                artworkImageView.image = image 
        } else { 
            guard let developerToken = appleMusicManager.fetchDeveloperToken() else {print("oops");return}
            let searchTypes = "songs"
            var searchURLComponents = URLComponents()
            searchURLComponents.scheme = "https"
            searchURLComponents.host = "api.music.apple.com"
            searchURLComponents.path = "/v1/catalog/"
            searchURLComponents.path += "\(authorizationManager.cloudServiceStoreFrontCountryCode)"
            searchURLComponents.path += "/search"
            let expectedArtist = artist?.replacingOccurrences(of: " ", with: "+")  //Changes here!
            let artistExpected = expectedArtist?.replacingOccurrences(of: "&", with: "")  //Changes here!
            let expectingArtist = artistExpected?.replacingOccurrences(of: "++", with: "+")  //Changes here!
            let expectedAlbum = albumTitle?.replacingOccurrences(of: " ", with: "+")  //Changes here!
            searchURLComponents.queryItems = [
                    URLQueryItem(name: "term", value: (expectingArtist! + "-" + expectedAlbum!)),
                    URLQueryItem(name: "types", value: searchTypes)
                ]  //Changes here!
            var request = URLRequest(url: searchURLComponents.url!)
            request.httpMethod = "GET"
            request.addValue("Bearer \(developerToken)", forHTTPHeaderField: "Authorization")
            let dataTask = URLSession.shared.dataTask(with: request) {
                (data, response, error) in
                print(response!)
                if let searchData = data {
                    guard let results = try? self.appleMusicManager.processMediaItemSections(searchData) else { return}
                    self.mediaItem = results
                    let album = self.mediaItem[0][0]
                    let albumArtworkURL = album.artwork.imageUrl(self.artworkImageView.frame.size)
                    if let image = self.imageManager.cachedImage(url: albumArtworkURL) {
                        print("using cached image")
                        self.artworkImageView.image = image
                    }
                    else {
                        self.imageManager.fetchImage(url: albumArtworkURL) {(image) in
                            print("fetching image")
                            self.artworkImageView.image = image
                        }
                    }
                }
            }
            dataTask.resume()
        }
    } else { // Need to set it to some kind of default values
        artworkImageView.image = nil
        songArtistNameLabel.text = " "
        songTitleLabel.text = " "
        songAlbumLabel.text = " "
        }
    }
}
zpqajqem

zpqajqem3#

MediaItem类中有一个名为MPMediaItemPropertyArtwork的属性。您可以通过以下方式检索相册的图稿:

MPMediaItemArtwork *artwork = [mediaItem valueForProperty:MPMediaItemPropertyArtwork];
UIImage *albumImage = [itemArtwork imageWithSize:cgSizeYouWant];
nfeuvbwi

nfeuvbwi4#

我发现最好的方法是使用从目录中获取歌曲的Apple Music API请求documented here
你只需要传入歌曲标识符(用于播放的标识符)和用于播放歌曲的店面标识符,这样总是能得到准确的结果,而应答器使用的搜索请求可能会失败。

yzuktlbb

yzuktlbb5#

有了SwiftUI,一切变得超级简单-

if let artwork = mediaItem.artwork {
     ArtworkImage(artwork, width: 85) // or whatever width you need. 
         .cornerRadius(10)
}

相关问题