这可能是重复的问题,但我花了很多时间来解决问题。 我将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:NSURL = urls.first as! NSURL as! NSURL{
let yourFinalVideoURL = documentDirectory.appendingPathComponent(downs[i])
let asset : AVURLAsset = 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
在我看来,当我试图获取我的视频文件的网址时,我做错了。但是如何解决这个问题。我尝试了很多东西。甚至我检查文件是否存在。它存在于何处。
我也试试
AVAsset(url: URL.init(url: yourFinalVideoURL)!)
不幸的是它不起作用..
无论如何,谢谢你的解决方案......
答案 0 :(得分:4)
您不应将自己的网址投射到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)