如何在iOS 11的Swift中获取FLAC文件元数据?

时间:2018-09-11 13:15:33

标签: ios swift flac

我需要获取FLAC文件的元数据。我尝试了以下代码:

let item = AVPlayerItem(url: URL(fileURLWithPath: path))
    let commonMetadata = item.asset.commonMetadata

    songInfo[ARTIST_NAME] = "Unknown"
    songInfo[GENRE_NAME] = "Unknown"
    songInfo[ALBUM_NAME] = "Unknown"
    songInfo[PLAY_COUNT] = "0"

    for metadataItem in commonMetadata {
        switch metadataItem.commonKey?.rawValue ?? "" {
        case "type":
            songInfo[GENRE_NAME] = metadataItem.stringValue
        case "albumName":
            songInfo[ALBUM_NAME]  = metadataItem.stringValue
        case "artist":
            songInfo[ARTIST_NAME] = metadataItem.stringValue
        default: break
        }
    } 

但这不适用于FLAC文件。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:5)

只需使用AudioToolbox API:

func audioFileInfo(url: URL) -> NSDictionary? {
    var fileID: AudioFileID? = nil
    var status:OSStatus = AudioFileOpenURL(url as CFURL, .readPermission, kAudioFileFLACType, &fileID)

    guard status == noErr else { return nil }

    var dict: CFDictionary? = nil
    var dataSize = UInt32(MemoryLayout<CFDictionary?>.size(ofValue: dict))

    guard let audioFile = fileID else { return nil }

    status = AudioFileGetProperty(audioFile, kAudioFilePropertyInfoDictionary, &dataSize, &dict)

    guard status == noErr else { return nil }

    AudioFileClose(audioFile)

    guard let cfDict = dict else { return nil }

    let tagsDict = NSDictionary.init(dictionary: cfDict)

    return tagsDict
}

示例输出:

- 0 : 2 elements
    * key : artist
    * value : Blue Monday FM
- 1 : 2 elements
    * key : title
    * value : Bee Moved
- 2 : 2 elements
    * key : album
    * value : Bee Moved
- 3 : 2 elements
    * key : approximate duration in seconds
    * value : 39.876
- 4 : 2 elements
    * key : source encoder
    * value : reference libFLAC 1.2.1 win64 200807090

答案 1 :(得分:0)

就我而言,我使用了https://github.com/CodeEagle/APlay。您可以编写此代码来获取元数据。

let mediaPlayer = APlay()
mediaPlayer.play("local_document_path/file.flac")
print(a.metadatas)

//输出

[APlay.MetadataParser.Item.year("2009"), APlay.MetadataParser.Item.album("Music From Braid"), APlay.MetadataParser.Item.track("03"), APlay.MetadataParser.Item.title("Lullaby Set"), APlay.MetadataParser.Item.artist("Kammen & Swan"), APlay.MetadataParser.Item.genre("Folk, World, & Country/Stage & Screen/Soundtrack")]