Get the accurate duration of a video
if let url = Bundle.main.url(forResource: "small", withExtension: "mp4") {
let asset = AVAsset(url: url)
let duration = asset.duration
let durationTime = CMTimeGetSeconds(duration)
let minutes = durationTime/60
let seconds = durationTime%60
let videoDuration = "\(minutes):\(seconds)"
print(videoDuration)
}
This works for me:
import AVFoundation
import CoreMedia
...
if let url = Bundle.main.url(forResource: "small", withExtension: "mp4") {
let asset = AVAsset(url: url)
let duration = asset.duration
let durationTime = CMTimeGetSeconds(duration)
print(durationTime)
}
For the video here it prints "5.568" which is correct.
Edit from comments:
A video that returns 707
seconds when divided by 60 sec/min
is 11.78
. This is 11.78 minutes, or 11 minutes and 0.78min * 60sec/min = 47sec
, total is 11 min 47 sec