How can I get FLAC file metadata in Swift on iOS 11?

落花浮王杯 提交于 2021-02-07 12:35:50

问题


I need to get metadata of an FLAC file. I tried following code:

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
        }
    } 

But this is not working for a FLAC file. Any help will be appreciated.


回答1:


Just use 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
}

Example output:

- 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



回答2:


In my case I have used https://github.com/CodeEagle/APlay. You can write this code to get metadata .

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

// output

[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")]


来源:https://stackoverflow.com/questions/52276830/how-can-i-get-flac-file-metadata-in-swift-on-ios-11

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!