获取准确的视频时长 [英] Get the accurate duration of a video

查看:138
本文介绍了获取准确的视频时长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个播放器,我想列出所有文件,并在所有文件的前面列出视频的时长.

唯一的问题是我没有获得正确的视频时长,有时返回的时长完全错误.

我尝试了以下解决方案:

 让资产= AVAsset(URL:"video.mp4")设持续时间= asset.duration.seconds 

因此,时间有时会给一个值,有时会给另一个值.如果有人知道可能的解决方案,我很高兴听到.

我已经使用一种可能的解决方案更新了代码,但是效果不佳,

 让资产= AVAsset(网址:url)设持续时间= asset.duration让durationTime = CMTimeGetSeconds(持续时间)让分钟= Double(durationTime/60) 

我尝试了一段时长为11:47分钟的视频,它返回了我= 11:78,那么视频怎么会有11分78秒呢?

所以我认为问题出在视频上,我又选择了1:16分钟的另一个视频,返回的值又是1:26(错了10秒)

解决方案

这对我有用:

 导入AVFoundation导入CoreMedia...如果让url = Bundle.main.url(forResource:"small",withExtension:"mp4"){让资产= AVAsset(URL:URL)设持续时间= asset.duration让durationTime = CMTimeGetSeconds(持续时间)打印(durationTime)} 

对于视频此处,它会打印"5.568",这是正确的./p>

从评论中

除以 60秒/分钟时返回 707 秒的视频是 11.78 .这是11.78分钟或11分钟,而 0.78min * 60sec/min = 47sec ,总计为 11分钟47秒

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)

解决方案

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

这篇关于获取准确的视频时长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆