如何使用swift获取当前播放音乐的专辑封面?

时间:2015-03-11 05:11:55

标签: ios swift

我正在尝试使用当前在音乐播放器上播放的歌曲的专辑封面创建UIImageView。我找到的所有资源都是在objective-c(我不知道)或不工作(也许我没有正确实现)。

我目前正在尝试使用此代码执行此操作:

class ViewController: UIViewController {

@IBOutlet weak var backgroundAlbum: UIImageView!



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    backgroundAlbum.image = MPMediaItemArtwork()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

但我在行

中收到错误
backgroundAlbum.image = MPMediaItemArtwork()

2 个答案:

答案 0 :(得分:2)

试试这个:

//this method is called after you picked a song from music library
func mediaPicker(mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {

    dismissViewControllerAnimated(true, completion: nil)

    //get current song
    let currentSong: MPMediaItem = mediaItemCollection.items[0]

    if let artwork: MPMediaItemArtwork = currentSong.valueForProperty(MPMediaItemPropertyArtwork) as? MPMediaItemArtwork{
        albumArt.image = artwork.imageWithSize(CGSize(width: x, height: y))
    }

答案 1 :(得分:0)

以下是我发现的方法:

    //Grab the controller
    let sysMP : MPMusicPlayerController & MPSystemMusicPlayerController = MPMusicPlayerController.systemMusicPlayer;

    //Grab current playing
    let currItem : MPMediaItem? = sysMP.nowPlayingItem;

    //Grab currItem's artwork
    let image : UIImage? = currItem?.artwork?.image(at: CGSize(width: 200, height: 200));

这是一个有用的参考: