【问题标题】:Audio Information of Current Track iOS Swift当前曲目iOS Swift的音频信息
【发布时间】:2023-11-14 08:54:01
【问题描述】:

假设正在播放一首曲目(通过任何应用程序),我想获取歌曲信息,例如名称。当您锁定手机时,它会与专辑封面一起显示在您的屏幕上。如何使用 swift 获取该信息?

【问题讨论】:

标签: ios swift avaudioplayer


【解决方案1】:

这是获取音频信息的示例函数:

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

}

希望这会有所帮助。

【讨论】:

  • 现在还有其他问题吗?
  • 就这一行:让metadataList = playerItem.asset.metadata as! [AVMetadataItem],我收到错误:致命错误:在展开可选值时意外发现 nil。任何提示?非常感谢您的帮助
  • 这是否捕获标题/艺术家/等。在任何播放歌曲的应用上?
  • 我认为这不能回答问题。您只是在设置MPNowPlayingInfoCenter,而问题是您是否可以访问其他应用程序设置的数据。我也在寻找那个答案 - 似乎无法访问另一个应用程序设置的 MPNowPlayingInfoCenter 信息 - 总是返回 nil。