映射 Documents 目录下的 mp3 并转换为 AVPlayerItems
Map mp3 s in Documents directory and convert to AVPlayerItems
我正在使用此方法将主包路径中的 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)
如何自动转换 Documents 目录中存在的所有 mp3?
您可以使用 FileManager 的 contentsOfDirectory(of: URL)
方法获取文档目录中的所有文件并映射包含 mp3 路径扩展的文件:
let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
let playesItems = try FileManager.default.contentsOfDirectory(at: documents, includingPropertiesForKeys: nil).compactMap {
[=10=].pathExtension == "mp3" ? [=10=].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)
}
}
Bundle
class 有一个方法 urls(forResourcesWithExtension:subdirectory:)
它将 return 捆绑包中的所有文件(或该捆绑包的子目录中的文件)与给定文件延期。使用它来搜索扩展名为 "mp3" 的所有文件,然后遍历它们并从每个文件中创建 AVPlayerItem
s。
我正在使用此方法将主包路径中的 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)
如何自动转换 Documents 目录中存在的所有 mp3?
您可以使用 FileManager 的 contentsOfDirectory(of: URL)
方法获取文档目录中的所有文件并映射包含 mp3 路径扩展的文件:
let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
let playesItems = try FileManager.default.contentsOfDirectory(at: documents, includingPropertiesForKeys: nil).compactMap {
[=10=].pathExtension == "mp3" ? [=10=].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)
}
}
Bundle
class 有一个方法 urls(forResourcesWithExtension:subdirectory:)
它将 return 捆绑包中的所有文件(或该捆绑包的子目录中的文件)与给定文件延期。使用它来搜索扩展名为 "mp3" 的所有文件,然后遍历它们并从每个文件中创建 AVPlayerItem
s。