Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the accurate duration of a video

Tags:

I'm making a player and I want to list all files and in front of all files I want to present the duration of the video.

The only problem is that I'm not getting the right video duration, sometimes it return a duration completely wrong.

I've tried the below solution:

let asset = AVAsset(url: "video.mp4")  let duration = asset.duration.seconds 

So that it, the time sometimes give a value sometimes another. if someone know a possible solution I'm glad to heard.

I have update the code using one possible solution but it didn't work well,

let asset = AVAsset(url: url)  let duration = asset.duration  let durationTime = CMTimeGetSeconds(duration)  let minutes = Double(durationTime / 60) 

I've tried with a video of 11:47 minutes of duration and it returns me = 11:78, how could a video have 11 minutes and 78 seconds?

So I think the problem is with the video, and I picked another video of 1:16 minutes and again the returned value is 1:26 (10 seconds wrong)

like image 475
Mr. James Avatar asked May 30 '17 16:05

Mr. James


People also ask

How do I find the length of a video in Python?

Count the total numbers of frames and frames per second of a given video by providing cv2. CAP_PROP_FRAME_COUNT and cv2. CAP_PROP_FPS to get() method. Calculate the duration of the video in seconds by dividing frames and fps.

How do I find the length of a video in HTML?

The duration property returns the length of the current audio/video, in seconds. If no audio/video is set, NaN (Not-a-Number) is returned.


2 Answers

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

like image 176
David S. Avatar answered Sep 21 '22 18:09

David S.


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)     } 
like image 38
Praveen kumar Avatar answered Sep 17 '22 18:09

Praveen kumar