Swift - 一些mp3文件元数据返回nil

时间:2017-03-22 21:22:25

标签: swift swift3 metadata mp3 avplayer

我的代码如下。对于某些文件,我获得了艺术家,标题等元数据,没有任何问题。对于其他文件,元数据列表为零,但是当我在编辑器中检查元数据时,如Tagger - 标题和其他元数据存在。此外,当我在外部编辑器中更改元数据至少一个键时 - 我的代码开始正常工作。

有人可以解释我哪里弄错了吗?

static func getBookInCatalog(url: URL) -> Book {

    let book = Book(url: url)
    let isDir: ObjCBool = false
    var directoryContents = [URL]()
    var totalTime: CMTime?
    var size: UInt64 = 0
    var chapters:Int = 0

    do {
        directoryContents = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: [])
    } catch let error as NSError {
        print(error.localizedDescription)
        return book
    }

    for item in directoryContents {

        if !isDir.boolValue {

            let result = appDelegate.fileTypes.filter { $0==item.pathExtension.lowercased() }
            if !result.isEmpty {

                chapters += 1

                let fileSize = (try! FileManager.default.attributesOfItem(atPath: item.path)[FileAttributeKey.size] as! NSNumber).uint64Value
                size += fileSize

                let playerItem = AVPlayerItem(url: item)
                let metadataList = playerItem.asset.commonMetadata
                let asset = AVURLAsset(url: item, options: nil)
                let audioDuration = asset.duration

                if let _ = totalTime {
                    totalTime = totalTime! + audioDuration
                } else {
                    totalTime = audioDuration
                }

                for metadata in metadataList {

                    guard let key = metadata.commonKey, let value = metadata.value else{
                        continue
                    }

                    switch key {
                    case "albumName":
                        if book.title == nil || book.title == "" {
                            book.title = (value as? String)!
                        }
                    case "artist":
                        if book.author == nil || book.author == ""  {
                            book.author = (value as? String)!
                        }
                    case "artwork" where value is NSData:
                        if book.image == nil {
                            book.image = UIImage(data: (value as! NSData) as Data)
                        }
                    default:
                        continue
                    }

                }
            }
        }
    }

    if let imageInsideCatalog = getImageFromFolder(url: url){
        book.image = imageInsideCatalog
    }

    if book.title == nil {
        book.title = url.deletingPathExtension().lastPathComponent
    }

    book.chapters = chapters
    book.totalTime = totalTime
    book.size = size


    return book
}

1 个答案:

答案 0 :(得分:0)

MP3元数据“标准”多年来经历了几次重大的迭代(见http://id3.org)。您的编辑器可能能够读取旧格式(AVURLAsset可能不支持)并使用最新/当前标准保存它们,这将使它们在任何更改后兼容。