使用JavaCV获取视频文件时长

1、做项目时,需要读取视频文件的时长,网上有很多通过自己写的JNI接口来实现,但由于项目使用了JavaCV和OpenCV,其中有一些处理视频的接口,所以还是想打算尽可能使用JavaCV和OpenCV来实现,经过查阅了相关的一些资料,实现了使用JavaCV获取视频文件时长的功能。

2、基本实现思路:获取视频的总帧数和每秒帧数(FPS),然后通过公式:视频总帧数/每秒帧数(FPS)=时长(单位秒)

3、实现代码如下:

package com.duoduo.javacv.samples;

import static com.googlecode.javacv.cpp.opencv_highgui.CV_CAP_PROP_FPS;
import static com.googlecode.javacv.cpp.opencv_highgui.CV_CAP_PROP_FRAME_COUNT;
import static com.googlecode.javacv.cpp.opencv_highgui.cvCreateFileCapture;
import static com.googlecode.javacv.cpp.opencv_highgui.cvGetCaptureProperty;
import static com.googlecode.javacv.cpp.opencv_highgui.cvReleaseCapture;

import java.io.File;

import com.googlecode.javacv.cpp.opencv_highgui.CvCapture;

/**
* 获取视频时长
*
* @author chengesheng
* @date 2013-5-22 下午11:15:25
* @note VideoFileLength
*/
public final class VideoFileLength {

public static void main(String[] argus) {
float len = getVideoFileLength("D:/J2EE/kdvp/webrtc/webapp/images/bike.avi");
System.out.println("Video length: " + len + " s");
}

public static float getVideoFileLength(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
return 0;
}

float len = 0;
CvCapture capture = cvCreateFileCapture(fileName);
try {
// 获取视频总帧数
long frameCount =(long) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT);
// 获取视频每秒帧数
long fps =(long) cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);

len = (float) frameCount / fps;
} catch (Exception e) {
e.printStackTrace();
} finally {
cvReleaseCapture(capture);
}
return len;
}
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值