I am trying to currently display album art for a locally saved .MP3 track in ImageView. Does anyone know how to get this work in Swift to do this?
I found this solution ( iOS AVFoundation: how to get artwork from an mp3 file? ), But the code is written in Objective C. I just want to capture the image embedded in my MP3 and display it in my ImageView.
I looked at the API documentation for MPMediaItemArtwork and found an example that also does what I try to execute in Objective-C also here ( http://www.codeitive.com/0zHjkUjUWX/not-able-to-get-the-uiimage-from -mpmediaitempropertyartwork.html ) but cannot find a solution. My code is as follows:
import UIKit import AVFoundation import MediaPlayer class ViewController: UIViewController { let audioPath:NSURL! = NSBundle.mainBundle().URLForResource("SippinOnFire", withExtension: "mp3") @IBOutlet var artistImage: UIImageView! @IBOutlet var trackLabel: UILabel! @IBOutlet var artistLabel: UILabel! @IBOutlet var sliderValue: UISlider! var player:AVAudioPlayer = AVAudioPlayer() @IBAction func play(sender: AnyObject) { let audioInfo = MPNowPlayingInfoCenter.defaultCenter() println(audioInfo) player.play() //println("Playing \(audioPath)") let playerItem = AVPlayerItem(URL: audioPath) let metadataList = playerItem.asset.metadata as! [AVMetadataItem] for item in metadataList { if let stringValue = item.value { println(item.commonKey) if item.commonKey == "title" { trackLabel.text = stringValue as? String } if item.commonKey == "artist" { artistLabel.text = stringValue as? String } if item.commonKey == "artwork" { if let audioImage = UIImage(data: item.value as! NSData) { let audioArtwork = MPMediaItemArtwork(image: audioImage) println(audioImage.description) } } } } } @IBAction func pause(sender: AnyObject) { player.pause() } @IBAction func stop(sender: AnyObject) { player.stop() player.currentTime = 0; } @IBAction func sliderChanged(sender: AnyObject) { player.volume = sliderValue.value } override func viewDidLoad() { super.viewDidLoad() var error:NSError? = nil player = AVAudioPlayer(contentsOfURL: audioPath!, error: &error) player.volume = 0.5; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
Here is a screenshot of my .mp3 file. As you can see, there really are album covers that are also visible in the βget infoβ section of the Finder. I also opened .mp3 in my iTunes to make sure, and confirmed that there are illustrations in the Get Info section there, as well as on the Jobs tab.
However, trying to use commonKey to assign an image to my ImageView, I found that there is no ordinary key for "artwork".

thanks
source share