iosswiftmpmediaitem

How to obtain audio metadata from music library mediaPicker and the Files app documentPicker?


In Swift 4, I can't figure out how to obtain audio metadata from the document picker when importing audio files and from the media picker when picking a media item from the user's media library. I am currently converting the url from both import methods to an AVAudioPlayer item. Can someone please let me know a method, even if I have to code it separately for both the mediaPicker and the documentPicker?

func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {

    for song in mediaItemCollection.items as [MPMediaItem] {

        // AVAudioPlayer
        let url = song.value(forProperty: MPMediaItemPropertyAssetURL) as? NSURL

        audioPlayer = try? AVAudioPlayer(contentsOf: url! as URL)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }

    mediaPicker.dismiss(animated: true, completion: nil)
}


    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
    guard controller.documentPickerMode == .import else { return }

    let fileURL = url

    let url = url.deletingPathExtension()

    audioPlayer = try? AVAudioPlayer(contentsOf: fileURL)
    audioPlayer.enableRate = true
    audioPlayer.prepareToPlay()
    audioPlayer.play()
    updateCurrentTrack()
}

Solution

  • Isn't it just a question of following thru the docs?

    1. Use the URL to form an AVAsset.

      https://developer.apple.com/documentation/avfoundation/avurlasset/1385698-init

    2. Now extract the metadata.

      https://developer.apple.com/documentation/avfoundation/avasset/1390498-commonmetadata

    3. Now get the desired metadata items:

      https://developer.apple.com/documentation/avfoundation/avmetadataitem/1385843-metadataitems

    4. You now have one or more AVMetadataItem objects. To retrieve a value, use asynchronous key-value loading:

      https://developer.apple.com/documentation/avfoundation/avasynchronouskeyvalueloading