FFmpeg框架系列:获取视频时长
1. 业务场景
业务需求:对上传的视频显示该时长。
2. FFmpeg框架处理视频信息
FFmpeg官网:http://ffmpeg.org/
3. 代码实现
3.1 windows安装FFmpeg
我在这篇五分钟JAVA代码教会你:FFmpeg实现视频试看(window版本)中写的十分详细,在windows/Linux安装FFmepg,此处我就不过多阐述了。
3.2 执行口令查看视频信息
在window中安装FFmpeg后,在cmd执行获取时长的命令即可:
F:\ffmpegDemo\ffmpeg\bin\ffmpeg.exe -i F://ffmpegDemo//test.mp4
PS:解压在windows本地的ffmpeg程序F:\ffmpegDemo\ffmpeg\bin\ffmpeg.exe以及存放在windows本地视频:F://ffmpegDemo//test.mp4
执行效果,如下:
3.3 Java解析信息并返回时长
通过FFmpeg执行命令行,获取返回的视频信息,通过java筛选到视频信息的目标数据,进行返回即可。
public static void main(String[] args) {
String timeLength = getVideoTime("F://ffmpegDemo//test.mp4","F:\\ffmpegDemo\\ffmpeg\\bin\\ffmpeg.exe");
if(timeLength.length()>0){
//字符串截取
timeLength =timeLength.substring(0,timeLength.indexOf("."));
}
System.out.println("视频时长:"+timeLength);
}
4. 贴出完成Demo
public class ExecWindowCMD {
public static void main(String[] args) {
String timeLength = getVideoTime("F://ffmpegDemo//test.mp4","F:\\ffmpegDemo\\ffmpeg\\bin\\ffmpeg.exe");
if(timeLength.length()>0){
//字符串截取
timeLength =timeLength.substring(0,timeLength.indexOf("."));
}
System.out.println("视频时长:"+timeLength);
}
/**
*获取视频时间
* @param video_path 视频路径
* @param ffmpeg_path ffmpeg安装路径
* @return
*/
public static String getVideoTime(String video_path, String ffmpeg_path) {
List<String> commands = new java.util.ArrayList<String>();
commands.add(ffmpeg_path);
commands.add("-i");
commands.add(video_path);
System.out.println("命令行:"+ffmpeg_path+" -i "+video_path);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commands);
final Process p = builder.start();
//从输入流中读取视频信息
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
//从视频信息中解析时长
String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
Pattern pattern = Pattern.compile(regexDuration);
Matcher m = pattern.matcher(sb.toString());
if (m.find()) {
//System.out.println(video_path+",视频时长:"+m.group(1)+", 开始时间:"+m.group(2)+",比特率:"+m.group(3)+"kb/s");
return m.group(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
执行效果如下:
视频源文件: