I would like to build an app that is able to get the name of what ever song is currently playing on the device (For example if I am using Spotify or any other player to play a song, the app should be able to get the title). The title should then just be stored in a variable.
I have not been successful in using nowPlayingInfo or MPMediaItemPropertyTitle.
Could someone please help me with this? This is the code that I have tried but I get an error:
Use of unresolved identifier 'playerItem'
for the line:
let metadataList = playerItem.asset.metadata as! [AVMetadataItem]
import UIKit
import MediaPlayer
import AVFoundation
class ViewController: UIViewController {
var url:NSURL!
let audioInfo = MPNowPlayingInfoCenter.default()
var nowPlayingInfo:[String:Any] = [:]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print(url.path!)
let metadataList = playerItem.asset.metadata as! [AVMetadataItem]
for item in metadataList {
if item.commonKey != nil && item.value != nil {
if item.commonKey == "title" {
println(item.stringValue)
nowPlayingInfo[MPMediaItemPropertyTitle] = item.stringValue
}
if item.commonKey == "type" {
println(item.stringValue)
nowPlayingInfo[MPMediaItemPropertyGenre] = item.stringValue
}
if item.commonKey == "albumName" {
println(item.stringValue)
nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = item.stringValue
}
if item.commonKey == "artist" {
println(item.stringValue)
nowPlayingInfo[MPMediaItemPropertyArtist] = item.stringValue
}
if item.commonKey == "artwork" {
if let image = UIImage(data: item.value as! NSData) {
nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: image)
println(image.description)
}
}
}
}
audioInfo.nowPlayingInfo = nowPlayingInfo