2019独角兽企业重金招聘Python工程师标准>>>
工作过程中有使用JAVA代码获取视频码率的场景,网上搜索了找到了利用ffmpeg来获取,ffmpeg组件中有ffprobe是专门用来获取视频相关信息的。
1、下载ffmpeg 官网:http://ffmpeg.org/,windows和linux版都有 解压即可使用,linux下注意给ffprobe授予755权限。
2、准备程序
第一步:获取视频格式信息
public static String getBitrate(String ffprobePath, String filePath) {
String cmd = ffprobePath + " -v quiet -print_format json -show_format -i " + filePath;
System.out.println(cmd);
try {
Runtime run = Runtime.getRuntime();
Process p = run.exec(cmd);
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String lineStr;
while ((lineStr = inBr.readLine()) != null)
sb.append(lineStr);
if (p.waitFor() != 0) {
if (p.exitValue() == 1)
System.err.println("命令执行失败!");
}
inBr.close();
in.close();
return analyseInfo(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
第二步:解析ffprobe返回的json结果,此处使用jackson解析
private static String analyseInfo(String json) throws IOException {
HashMap map = mapper.readValue(json, HashMap.class);
Map format = (Map) map.get("format");
String bitrate = (String) format.get("bit_rate");
return bitrate;
}
第三步、测试
@Test
public void test_get_bit_rate(){
String file = "D:\\server\\1414079044194DAW1XHPV.flv";
//String file = "F:\\迅雷下载\\N间谍.BD1280高清特效中英双字.mp4";
String ffprobe = "D:\\Soft\\ffmpeg\\bin/ffprobe.exe";
System.out.println(getBitrate(ffprobe , file));
}
第四步:测试结果
与通过迅雷影音看到的码率基本一致:
附: ffprobe获取的原始信息:
{
"format": {
"filename": "/root/tmp/1414079044194DAW1XHPV.flv",
"nb_streams": 2,
"nb_programs": 0,
"format_name": "flv",
"format_long_name": "FLV (Flash Video)",
"start_time": "0.134000",
"duration": "240.530000",
"size": "11033501",
"bit_rate": "366972",
"probe_score": 100,
"tags": {
"encoder": "Lavf53.24.2"
}
}
}