Audio Information of Current Track iOS Swift

不想你离开。 提交于 2019-12-19 11:18:39

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/31581242/audio-information-of-current-track-ios-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!