如何从 swift 5.3 中的 m4a 音频文件获取曲目 ID

How to get Track Id from m4a audio file in swift 5.3

我可以从音轨中获取一些信息,但不能获取音轨 ID。有人指出我如何获取曲目 ID 吗?我正在使用 xcode 12.3。谢谢!

func getM4aAudioDetails(afile: URL) {

        let song = Song(context: moc)
        let avasset = AVAsset(url: afile as URL) as AVAsset
        let metadata = avasset.metadata(forFormat: AVMetadataFormat.iTunesMetadata)
        let cmetadata = avasset.commonMetadata

        let titleItems = AVMetadataItem.metadataItems(from: metadata, withKey: "©nam", keySpace: AVMetadataKeySpace(rawValue: "itsk"))
        if let data = titleItems.first, let title = data.stringValue {
            song.title = title
        }

        let artistItems = AVMetadataItem.metadataItems(from: metadata, withKey: "©ART", keySpace: AVMetadataKeySpace(rawValue: "itsk"))
        if let data = artistItems.first, let artist = data.stringValue {
            song.artist = artist
        }

        let albumItems = AVMetadataItem.metadataItems(from: metadata, withKey: "©alb", keySpace: AVMetadataKeySpace(rawValue: "itsk"))
        if let data = albumItems.first, let album = data.stringValue {
            song.album = album
        }

        let trackItems = AVMetadataItem.metadataItems(from: metadata, withKey: "trkn", keySpace: AVMetadataKeySpace(rawValue: "itsk"))
        if let data = trackItems.first, let trackString = data.stringValue {
            
            song.track = Int64(trackString)!
            print("Track: \(song.track)")
        }

        let artworkItems = AVMetadataItem.metadataItems(from: cmetadata, filteredByIdentifier: .commonIdentifierArtwork)
        if let artworkItem = artworkItems.first {
            if let imageData = artworkItem.dataValue {
                //let image = NSImage(data: imageData)
                song.artwork = imageData as Data
                //print("image found")
            }
        }
        
        print("song title: \(song.title)")
        print("song artist: \(song.artist)")
        print("song name: \(song.album)")
        print("song track: \(song.track)")
    }

打印:(摘录)

您已经在 trackItems 中获得了曲目编号。但是它应该是 dataValue,而不是 stringValue

对于我的一首曲目,我看到 8 个字节,看起来像 4 个 16 位大端整数:

0x00000008000e0000

我的是 14 首曲目中的第 8 首,所以我猜你想要第二个整数。

下面是上述的更多轶事证据:
https://lists.apple.com/archives/cocoa-dev/2009/Oct/msg00952.html

你可以用这个做你想做的事(注意 keySpace/keys 的符号):

if let trackItem = AVMetadataItem.metadataItems(from: metadata, filteredByIdentifier: .iTunesMetadataTrackNumber).first,
   let data = trackItem.dataValue,
   data.count == 8 {
    let bytes = [UInt8](data)
    let trackNumber = ((Int)(bytes[2]) << 8) | (Int)(bytes[3])
    let totalTracks = ((Int)(bytes[4]) << 8) | (Int)(bytes[5])
    print("trackNumber: \(trackNumber)/\(totalTracks)")
}

N.B.: mp3/ID3 不同,在这种情况下你需要 id3/TRCK 并且它是一个包含整数的 stringValue