Search code examples
swiftavassetavurlasset

How to get video duration fro AVAsset in Swift


It might be duplicate question but I spent to much time for solution. I download a mp4 file to documentary directory. I can get all file names with this function:

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

And I want to get all of these file's time length. Let me show what I try:

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)
}

the output is

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

In my opinion I did wrong when I try to get url of my video file. But how to fix that. I try a lot of things. Even I check if the file is exist or not. Which its exist ofcourse.

Also I try

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

unfortunetely it does not work..


Solution

  • You shouldn't cast your url to NSURL. Just get your documents directory url, and append your filename and extension to it. Besides that you can get CMTime seconds property which is a double and use String(format:) method to properly display the time in "h m s" format:

    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)