iosswiftaudioaudio-playerartwork

Using Swift to display title of currently playing .MP3


I was wondering if there was a straight forward way of displaying the image and title of the currently playing MP3 file my music player is playing. My code is as follows and is very simple for this example. I am only wanting to test using one .MP3 that I've included in my project.

class ViewController: UIViewController {
    let audioPath:NSURL! = NSBundle.mainBundle().URLForResource("SippinOnFire", withExtension: "mp3")

    @IBOutlet var sliderValue: UISlider!
    var player:AVAudioPlayer = AVAudioPlayer()


    @IBAction func play(sender: AnyObject) {

        player.play()
        //println("Playing \(audioPath)")
    }
    @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.
    }


}

So far I am able to println the full path to the MP3 file but have not been able to use the display the image that is showing as the cover art for my MP3 in the project or to display only the title of the track playing. Could someone help me out with this?


Solution

  • you need to add the import statement for Media player and set the General Media Item Property Keys for nowPlayingInfo property. For the MPMediaItemPropertyArtwork you need to take a look at this MPMediaItemArtwork

    import MediaPlayer
    
    let audioInfo = MPNowPlayingInfoCenter.defaultCenter()
    let audioName = audioPath.lastPathComponent!.stringByDeletingPathExtension
    audioInfo.nowPlayingInfo = [ MPMediaItemPropertyTitle: audioName, MPMediaItemPropertyArtist:"artistName"]
    

    To extract the metadata from your mp3 you need to create an AVPlayerItem and access its asset commonMetadata property

    let playerItem = AVPlayerItem(URL: audioPath)
    let metadataList = playerItem.asset.commonMetadata as! [AVMetadataItem]
    for item in metadataList {
        if item.commonKey == "title" {
            println("Title = " + item.stringValue)
        }
        if item.commonKey == "artist" {
            println("Artist = " + item.stringValue)
        }
    }       
    

    Note: You will have to invoke beginReceivingRemoteControlEvents() otherwise it will not work on the actual device.

    override func viewDidLoad() {
        super.viewDidLoad()
        UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
    }