Let's say a track is playing (through any app), and I want to get the song information, such as the name. It shows up on your screen when you lock the phone, along with the album cover. How can I get that information using swift?
Asked
Active
Viewed 2,551 times
2
-
Duplicate of http://stackoverflow.com/questions/23515633/get-current-track-playing-on-control-center-ios, the answer is not in swift but Objective-C. Check doc here: https://developer.apple.com/library/ios/documentation/MediaPlayer/Reference/MPNowPlayingInfoCenter_Class/ – Hugues BR Jul 23 '15 at 07:55
1 Answers
-2
Here is example function to get audio Info:
import MediaPlayer
var url:NSURL!
let audioInfo = MPNowPlayingInfoCenter.defaultCenter()
var nowPlayingInfo:[NSObject:AnyObject] = [:]
func fetchMP3Info() {
let playerItem = AVPlayerItem(URL: url) //this will be your audio source
println(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
}
Hope this will help.

Dharmesh Kheni
- 71,228
- 33
- 160
- 165
-
-
On this line: let metadataList = playerItem.asset.metadata as! [AVMetadataItem], I"m getting the error: fatal error: unexpectedly found nil while unwrapping an Optional value. Any tips? Thanks so much for your help – shaydawg Jul 24 '15 at 01:37
-
1Does this capture the title/artist/etc. on any app playing a song? – stackerleet Dec 29 '15 at 08:25
-
5I don't think this answers the question. You are merely setting the `MPNowPlayingInfoCenter`, while the question is asking if you can access the data set by other apps. I am looking for that answer as well - it seems that its not possible to access the `MPNowPlayingInfoCenter` information set by another app - always returns nil. – Aram H.B. Jan 16 '17 at 11:51