如何从应用程序的文档目录中检索音乐的艺术家信息

时间:2019-08-25 08:24:47

标签: ios swift swift5

我正在制作音乐播放器,它支持将音乐文件从计算机的浏览器上传到此应用程序的文档目录。然后在tableViewController中显示所有音乐。

我的问题是,如何从这些音乐文件中获取诸如艺术家姓名,专辑名称之类的信息,例如mp3格式?请帮忙。

使用MPMediaQuery.artists(),MPMediaQuery.albums()找到了一些解决方案,但它们可能仅对设备的媒体库有效。

代码:

// FileOperation.swift,获取音乐计数,音乐名称和大小。

import Foundation

class FileOperation {

    var musicCount = 0
    var fileNames = [String]()
    var fileSize = 0


    init() {
        do {
            // Get the document directory url
            let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

            // Get the directory contents urls (including subfolders urls)
            let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
            print(directoryContents)
            musicCount = directoryContents.count

            // if you want to filter the directory contents you can do like this:
            let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
            print("mp3 urls:",mp3Files)
            fileNames = mp3Files.map{ $0.lastPathComponent }
            print("mp3 list:", fileNames)

            // get file size from URL
            let resources = try directoryContents[0].resourceValues(forKeys: [.fileSizeKey])

            fileSize = resources.fileSize!
            print("fileSize", fileSize)

        } catch {
            print(error)
        }
    }

// Table View Controller,要在cell.detailTextLabel?.text = "details"中显示艺术家名称

import UIKit


class SongsTableViewController: UITableViewController {

    var musicCount = 0
    var fileNames = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // get songs number
        let fileOp = FileOperation()
        musicCount = fileOp.musicCount

        // get songs list [String]
        fileNames = fileOp.fileNames
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return musicCount
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)

        cell.textLabel?.text = fileNames[indexPath.row]
        cell.detailTextLabel?.text = "details"

        return cell
    }

/// 2019年8月27日更新,添加代码以检索音乐的艺术作品

 for url in mp3Files {
                let asset = AVAsset(url: url)
                let metaData = asset.metadata
                // print("metaData:", metaData.description)
                // print("=====================================================================")
                if let artist = metaData.first(where: {$0.commonKey == .commonKeyArtist}), let value = artist.value as? String {
                    artistName = value
                    artistList.append(artistName)
                    // print("Artist:",artistName)
                }

                if let album = metaData.first(where: {$0.commonKey == .commonKeyAlbumName}), let value = album.value as? String {
                    albumName = value
                    // print("Album:",albumName)
                }

                if let albumImage = metaData.first(where: {$0.commonKey == .commonKeyArtwork}), let value = albumImage.value as? Data {
                    albumArtWork = UIImage(data: value)
                    artWorkList.append(albumArtWork!)
                } else {
                    print("artWork is not found!")
                }
            }

1 个答案:

答案 0 :(得分:0)

您可以使用AVKit

获取MP3标签。
import AVKit

let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
for url in mp3Files {   
    let asset = AVAsset(url: url)
    let metaData = asset.metadata
    if let artist = metaData.first(where: {$0.commonKey == .commonKeyArtist}), let value = artist.value as? String {
        print("Artist:",value)
    }
    if let album = metaData.first(where: {$0.commonKey == .commonKeyAlbumName}), let value = album.value as? String {
        print("Album:",value)
    }
}