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

How to retrieve music's artist information from app's document directory

我正在做一个音乐播放器,它支持从电脑浏览器上传音乐文件到这个应用程序的文档目录。然后在 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{ [=10=].pathExtension == "mp3" }
            print("mp3 urls:",mp3Files)
            fileNames = mp3Files.map{ [=10=].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: {[=12=].commonKey == .commonKeyArtist}), let value = artist.value as? String {
                    artistName = value
                    artistList.append(artistName)
                    // print("Artist:",artistName)
                }

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

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

您可以通过 AVKit

获取 MP3 标签
import AVKit

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