如何在 Swift 中从 AVAsset 获取视频时长

How to get video duration fro AVAsset in Swift

这可能是重复的问题,但我花了很多时间来解决。我将 mp4 文件下载到文档目录。我可以用这个函数获取所有文件名:

func listFilesFromDocumentsFolder() -> [String]? {
    let fileMngr = FileManager.default;
    let docs = fileMngr.urls(for: .documentDirectory, in: .userDomainMask)[0].path
    return try? fileMngr.contentsOfDirectory(atPath: docs)
}

我想获取所有这些文件的时间长度。让我展示一下我的尝试:

var downs = listFilesFromDocumentsFolder()!
for i in 0...downs.count - 1 {
    if downs[i] == ".DS_Store" {
                continue
    }
    let fileManager = FileManager.default
    let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
    if let documentDirectory= urls.first as! NSURL as! NSURL { 
         let yourFinalVideoURL = documentDirectory.appendingPathComponent(downs[i])
         let asset = AVURLAsset(url: yourFinalVideoURL!) as AVURLAsset
         let totalSeconds = Int(CMTimeGetSeconds(asset.duration))
         let minutes = totalSeconds / 60
         let seconds = totalSeconds % 60
         let mediaTime = String(format:"%02i:%02i",minutes, seconds)
         print(yourFinalVideoURL)
         print(mediaTime)
}

输出是

Optional(file:///Users/utf8/Library/Developer/CoreSimulator/Devices/D4F341F1-38A2-498B-99F0-076BE9164A5C/data/Containers/Data/Application/718927F7-4E39-43A8-B760-2A468F82A10F/Documents/viki50102klr.mp4)
00:00

我认为我在尝试获取 url 视频文件时做错了。但是如何解决这个问题。我尝试了很多东西。即使我检查文件是否存在。它当然存在。

我也试试

AVAsset(url: URL(url: yourFinalVideoURL)!)

不幸的是它不起作用..

您不应该将 url 转换为 NSURL。只需获取您的文档目录 url,并将您的文件名和扩展名附加到它。除此之外,您可以获得 CMTime 秒 属性 这是一个双精度并使用 String(format:) 方法以 "h m s" 格式正确显示时间:

let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let videoURL = documentDirectory.appendingPathComponent(downs[i])    
let duration = AVURLAsset(url: videoURL).duration.seconds
    print(duration)
let time: String
if duration > 3600 {
    time = String(format:"%dh %dm %ds",
        Int(duration/3600),
        Int((duration/60).truncatingRemainder(dividingBy: 60)),
        Int(duration.truncatingRemainder(dividingBy: 60)))
} else {
    time = String(format:"%dm %ds",
        Int((duration/60).truncatingRemainder(dividingBy: 60)),
        Int(duration.truncatingRemainder(dividingBy: 60)))
}
print(time)