java如何获取视频的时长?
时间: 2023-09-01 21:07:37 浏览: 92
Java可以使用FFmpeg或JavaCV等第三方库来获取视频的时长。以下是使用JavaCV获取视频时长的示例代码:
```java
import org.bytedeco.javacpp.avformat;
import org.bytedeco.javacv.FFmpegFrameGrabber;
public class VideoDuration {
public static void main(String[] args) {
String videoPath = "your_video_path.mp4";
long duration = getVideoDuration(videoPath);
System.out.printf("Video duration: %d seconds", duration);
}
public static long getVideoDuration(String videoPath) {
try {
FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoPath);
grabber.start();
avformat.AVStream stream = grabber.getFormatContext().streams(0);
long duration = stream.duration() / 1000000L;
grabber.stop();
return duration;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
}
```
其中,`FFmpegFrameGrabber`是JavaCV提供的一个类,用于读取视频文件。`getVideoDuration`方法中,通过`avformat.AVStream`的`duration()`方法获取视频流的时长,单位为微秒,需要除以1000000L转换为秒。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)