将mp3映射到Documents目录并转换为AVPlayerItems

时间:2018-09-02 23:33:24

标签: swift avfoundation avplayer avplayeritem

我正在使用此方法将主捆绑包路径中的mp3转换为avplayer项:

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

如何自动转换文档目录中存在的每个mp3?

2 个答案:

答案 0 :(得分:2)

您可以使用FileManager的contentsOfDirectory(of: URL)方法来获取文档目录中的所有文件,并映射包含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) }

别忘了将那些助手添加到您的项目中:

import UIKit
import AVKit

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

答案 1 :(得分:1)

Bundle类具有方法urls(forResourcesWithExtension:subdirectory:),该方法将返回束中(或束的子目录中)具有给定文件扩展名的所有文件。使用它搜索扩展名为“ mp3”的所有文件,然后遍历它们并从每个文件中创建AVPlayerItem