[swift] 사운드 파일의 메타데이터 가져오기

iOS 앱을 개발하다 보면 사운드 파일의 메타데이터를 가져와야 할 때가 있습니다. 그러나 Swift에서는 이를 처리하는 간단한 방법을 제공하지 않습니다. 이 글에서는 사운드 파일의 메타데이터를 가져오는 방법을 알아보겠습니다.

AVFoundation의 활용

AVFoundation 프레임워크는 사운드 및 비디오 미디어 작업을 하기 위한 기능을 제공합니다. 이를 사용하여 사운드 파일의 메타데이터를 가져올 수 있습니다.

import AVFoundation

func getSoundMetadata(fileURL: URL) -> AVAssetMetadata {
    let asset = AVAsset(url: fileURL)
    
    guard let metadata = asset.commonMetadata else {
        return []
    }
    
    return metadata
}

위의 예제 코드에서 getSoundMetadata 함수는 주어진 파일 URL에서 사운드 파일의 메타데이터를 가져옵니다. AVAsset 클래스는 사운드 파일에 대한 정보와 메타데이터를 제공하는 객체입니다. commonMetadata 속성을 사용하여 메타데이터에 액세스할 수 있습니다. 이 속성은 AVMetadataItem 객체의 배열을 반환합니다.

메타데이터 사용 예제

아래는 가져온 메타데이터를 사용하는 예제입니다.

let fileURL = URL(fileURLWithPath: "path_to_sound_file")

let metadata = getSoundMetadata(fileURL: fileURL)

for item in metadata {
    if item.commonKey == AVMetadataKey.commonKeyTitle {
        if let title = item.value as? String {
            print("Title: \(title)")
        }
    }
    
    if item.commonKey == AVMetadataKey.commonKeyArtist {
        if let artist = item.value as? String {
            print("Artist: \(artist)")
        }
    }
    
    // 추가적인 메타데이터 항목들을 처리할 수 있습니다.
    // ...
}

위의 예제에서는 AVMetadataKey.commonKeyTitleAVMetadataKey.commonKeyArtist를 사용하여 제목과 아티스트를 출력합니다. 다른 메타데이터 항목에 액세스하려면 해당 키를 사용하면 됩니다.

결론

Swift에서는 AVFoundation을 사용하여 사운드 파일의 메타데이터를 가져올 수 있습니다. 이를 활용하여 앱에서 사운드 파일의 제목, 아티스트, 앨범 등의 정보를 사용할 수 있습니다.