Search code examples
swiftavfoundationavplayeravplayeritem

Map mp3 s in Documents directory and convert to AVPlayerItems


I am using this method to convert an mp3 in my main bundle path to an avplayer item:

let path = Bundle.main.path(forResource: "Baroon", ofType: "mp3")
let url = URL(fileURLWithPath: path!)
let asset = AVAsset(url: url)
let item = AVPlayerItem(asset: asset)

How can I convert every mp3 that exist in the Documents directory automatically?


Solution

  • You can use FileManager's contentsOfDirectory(of: URL) method to get all files in your documents directory and map the ones that contains the mp3 pathExtension:

    let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    do {
        let playesItems = try FileManager.default.contentsOfDirectory(at: documents, includingPropertiesForKeys: nil).compactMap {
            $0.pathExtension == "mp3" ? $0.asset.playerItem : nil
        }
        for item in playesItems {
            print(item.asset.duration)
        }
    } catch { print(error) }
    

    Don't forget to add those helpers to your project:

    import UIKit
    import AVKit
    
    extension URL {
        var asset: AVAsset {
            return AVAsset(url: self)
        }
    }
    extension AVAsset {
        var playerItem: AVPlayerItem {
            return AVPlayerItem(asset: self)
        }
    }