ffmpeg下载和实战获取音视频时长
目录
一、介绍和下载
(1)介绍
(2)下载
二、实战演示
(1)通过ffmpeg获取音视频的时长
1. 命令行方式:
2. java代码实现:
一、介绍和下载
(1)介绍
FFmpeg 是一个跨平台的开源音视频处理解决方案,它包含了庞大的库集合和命令行工具,用于处理多媒体内容(音频、视频、字幕等)。
(2)下载
Download FFmpeghttps://ffmpeg.org/download.html
二、实战演示
(1)通过ffmpeg获取音视频的时长
1. 命令行方式:
ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 D:\\Desktop\\测试音频\\119.mp3
- -v error:只显示错误信息,避免多余输出。
- -show_entries format=duration:仅显示时长信息。
- -of default=noprint_wrappers=1:nokey=1:简化输出格式,只返回数值(单位:秒)。
2. java代码实现:
package com.grmdcxy;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;public class FFmpegDuration {public static void main(String[] args) {String mediaPath = "D:\\Desktop\\教程视频\\框架讲解\\旋转骰子效果.mp4";double duration = getMediaDuration(mediaPath);System.out.println("音视频时长(秒): " + duration);System.out.println("音视频时长(HH:MM:SS): " + secondsToTime(duration));}/*** 调用 ffprobe 获取音视频时长(秒)*/public static double getMediaDuration(String filePath) {try {// 构建 ffprobe 命令String[] cmd = {"ffprobe","-v", "error","-show_entries", "format=duration","-of", "default=noprint_wrappers=1:nokey=1",filePath};// 执行命令并读取输出Process process = Runtime.getRuntime().exec(cmd);BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));String line = reader.readLine();if (line != null) {return Double.parseDouble(line);}} catch (IOException | NumberFormatException e) {e.printStackTrace();}return 0;}/*** 将秒数转换为 HH:MM:SS 格式*/public static String secondsToTime(double seconds) {int hours = (int) (seconds / 3600);int minutes = (int) ((seconds % 3600) / 60);int secs = (int) (seconds % 60);return String.format("%02d:%02d:%02d", hours, minutes, secs);}
}