如何显示流媒体Apple Music的专辑封面?

时间:2016-07-17 00:14:40

标签: ios objective-c swift media-player apple-music

在我的音乐播放器中使用iOS 9中的新Apple Music API(2016年5月12日发布)(很快,虽然我现在也熟悉Objective-C),但我可以显示来自流媒体歌曲的信息,但不是艺术品。我正在使用MediaPlayer,UIKit和StoreKit框架。我成功申请了AddToCloudMusicLibrary和MusicCatalogPlayback的授权。我成功地从Apple Music应用程序下载的歌曲中显示Apple Music图稿,以及我个人歌曲集中的艺术作品。我见过其他有问题的人,没有运气......

在我诉诸显示默认图像(无论如何需要进行错误处理)或从备用服务中提取之前,再尝试再次询问人们。任何帮助都会很棒!我的代码中并不是真的错误所以我不会显示它,除非请求帮助解决这个问题。

我第一次尝试发布代码......这就是我在名为Authorization的swift文件中所拥有的内容。我需要在任何地方引用此代码,还是应该在AppDelegate文件中?这是我项目中唯一不完全确定的部分。

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()
                    }
                }
            }
        }
    }
}

4 个答案:

答案 0 :(得分:5)

这是Apple Music当前API中的一个错误。正如您所提到的,不在用户库中而是从AM流式传输的歌曲将不会返回专辑封面。

你应该在bugreport.apple.com上提交一项功能增强功能(你也可以从6个月前的25413082开始使用。)

与此同时,您最好的选择是使用iTunes api检索专辑图片,遗憾的是,这并不能在100%的时间内返回正确的结果......

答案 1 :(得分:0)

在MediaItem类中,有一个名为 MPMediaItemPropertyArtwork 的属性。您将能够以下列方式检索相册的艺术作品:

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

答案 2 :(得分:0)

我在这方面挣扎了很长时间。如果这是一个实际的错误,我不确定,但是你不能像你期望的那样将UIImageView设置为nowPlayingItem。您必须从Apple Music服务API中提取图像。请参阅文档here。另请参阅Apple提供的示例项目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 = " "
        }
    }
}

答案 3 :(得分:0)

我发现最好的方法是使用目录Apple Music API请求documented here中的获取歌曲。

您只需要传入歌曲标识符(用于播放的标识符)和用于播放歌曲的店面标识符即可。与使用可能会失败的搜索请求的答案相比,这总是可以得到准确的结果。