Swift IOS:获得当前歌曲的标题

时间:2017-08-06 12:06:27

标签: ios swift avaudioplayer

我想构建一个能够获取当前正在播放的歌曲名称的应用程序(例如,如果我使用Spotify或任何其他播放器播放歌曲,该应用程序应该能够得到标题)。然后标题应该存储在变量中。

我没有成功使用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

1 个答案:

答案 0 :(得分:-2)

我想你错过了代码:var playerItem = AVPlayerItem(URL: url)

前面
 let metadataList = playerItem.asset.metadata as! [AVMetadataItem]

如果您在本地文件夹中有一些音乐,并且想要获得音乐的艺术作品,标题,艺术家和专辑,您可以创建一个名为Music的模型和一个获取musicArray的方法,其中包含您需要的信息。 这很容易,您可以使用var musics :[Music]?来保存viewController中的音乐,并使用方法获取按音乐标题(或您想要使用的其他属性)排序的音乐:

private func getMusics(){
        Music.getMusicList { [unowned self] (musics) in
            self.musics = musics.sorted{$0.title! < $1.title!}
        }
    }

在模型音乐文件中:

import Foundation
import UIKit
import AVFoundation

struct Music {
    var artwork   : UIImage?  
    var title     : String?   
    var artist    : String?   
    var album     : String?   
    var muscicURL : String?   

        init(artwork:UIImage,title:String,artist:String,album:String,muscicURL:String) {
        self.artwork = artwork
        self.title = title
        self.artist = artist
        self.album = album
        self.muscicURL = muscicURL

    }
 static func getMusicList(completion:@escaping ([Music]) -> Void){

        var musicImage  : UIImage?
        var musicTitle  : String?
        var musicArtist : String?
        var musicAlbum  : String?
        var musicURL    : String!

    var musics = [Music]()

    let folderURL = URL(fileURLWithPath: Bundle.main.resourcePath!)

    do {
        let songPaths = try FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)

        _ = songPaths.map({
            let songPath = $0.absoluteString
            if songPath.contains(".mp3"){

                musicURL = songPath
                let mp3Asset = AVURLAsset.init(url: URL(string:songPath)!)

                for metadataFormat in mp3Asset.availableMetadataFormats {
                    for metadataItem in mp3Asset.metadata(forFormat: metadataFormat){

                        if metadataItem.commonKey == "artwork",let imageData  = metadataItem.value as? Data{

                            musicImage = UIImage.init(data: imageData)!

                        }else if metadataItem.commonKey == "title",let title = metadataItem.value as? String {

                            musicTitle = title

                        }else if metadataItem.commonKey == "artist",let artist = metadataItem.value as? String {

                            musicArtist = artist

                        }else if metadataItem.commonKey == "albumName",let album = metadataItem.value as? String {

                            musicAlbum = album
                        }

                    }

                }
                let music = Music(artwork: musicImage!, title: musicTitle!, artist: musicArtist!, album: musicAlbum!,muscicURL:musicURL!)
                musics.append(music)

            }
        })
        completion(musics)
       // print(musics)

    } catch let error {
        print(error.localizedDescription)

    }
 }

}