Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the album artwork of the currently playing music using swift?

Tags:

ios

swift

I am trying to create a UIImageView with the album artwork of the song currently playing on a music player. All of the resources I have found are either in objective-c (which I don't know) or do not work (maybe I am not implementing it correctly).

I am currently trying to do this with this code:

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.
}

}

but I am getting an error in the line

backgroundAlbum.image = MPMediaItemArtwork()
like image 461
juancarlos Avatar asked Sep 14 '25 01:09

juancarlos


2 Answers

Try this:

//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))
    }
like image 178
Bao Pham Avatar answered Sep 15 '25 15:09

Bao Pham


Here's how I found to do it:

    //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));

Here is a useful reference:

  • MPMusicPlayerController - Media Player | Apple Developer Documentation
like image 25
J-Dizzle Avatar answered Sep 15 '25 16:09

J-Dizzle