我想構建一個應用程序,可以獲取設備上正在播放的歌曲的名稱(例如,如果我使用Spotify或任何其他播放器播放一首歌曲,應用程序應該能夠獲得標題)。標題應該只存儲在一個變量中。Swift IOS:獲取當前播放歌曲的標題
我還沒有成功地使用nowPlayingInfo或MPMediaItemPropertyTitle。
有人可以幫助我嗎?這是我嘗試過的代碼,但是我得到一個錯誤(使用未解析的標識符'playerItem'):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
你能分享一些代碼,你試過嗎? – Sal
Paul我添加了一些代碼 – Kenneth