第一步,解析視頻文件
private static String processVideo(String filePath) {
List<String> commend=new java.util.ArrayList<String>();
commend.add("ffmpeg");//可以設置環境變量從而省去這行//d:\ffmpeg\ffmpeg.exe
commend.add("-i");
commend.add(filePath);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
Process p= builder.start();
BufferedReader buf = null; // 保存ffmpeg的輸出結果流
String line = null;
buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuffer sb= new StringBuffer();
while ((line = buf.readLine()) != null) {
sb.append(line);
continue;
}
p.waitFor();//這裏線程阻塞,將等待外部轉換進程運行成功運行結束後,才往下執行
return sb.toString();
} catch (Exception e) {
System.out.println("ffmpeg解析視頻文件【" + filePath +"】失敗!");
return null;
}
}
第二步,獲取相關metadata,獲取視頻的旋轉角度
private static String getRotate() {
String rotate = "";
String result = processVideo(videoPath);
System.out.println(result);
if(StringUtils.isNotEmpty(result)){
PatternCompiler compiler =new Perl5Compiler();
try {
String regexRotate ="rotate\\s*:\\s*(\\w*)\\s*";
Pattern patternRotate = compiler.compile(regexRotate, Perl5Compiler.CASE_INSENSITIVE_MASK);
PatternMatcher matcherRotate = new Perl5Matcher();
if(matcherRotate.contains(result, patternRotate)){
MatchResult re = matcherRotate.getMatch();
rotate = re.group(1);
System.out.println("rotate:"+rotate);
}
} catch (MalformedPatternException e) {
System.out.println("獲取【" + videoPath +"】視頻信息失敗!");
}
System.out.println("獲取【" + videoPath +"】視頻信息成功!");
}else{
System.out.println("執行成功!但未獲取到【" + videoPath +"】視頻信息!");
}
return rotate;
}
第三步,根據rotate角度信息,調用旋轉命令
private static boolean rotate90mp4(String rotate) {
List<String> commend = new ArrayList<String>();
//ffmpeg -i demo.mp4 -vf "transpose=1" o.mp4
try {
Runtime runtime = Runtime.getRuntime();
// String cmd = " ffmpeg -i "+ videoPath + " -vf \"transpose=1\" d:\\out\\vertical.mp4";
StringBuffer buf = new StringBuffer();
buf.append(" ffmpeg ");
buf.append(" -i ");
buf.append(videoPath);
if(!StringUtils.isBlank(rotate)){
buf.append(" -vf ");
if(rotate.equals("90"))
buf.append(" \"transpose=1\" ");
else if(rotate.equals("180"))
buf.append(" \"transpose=2,transpose=2\" ");
else if(rotate.equals("270"))
buf.append(" \"transpose=2\" ");
}
buf.append(destPath);
runtime.exec(buf.toString());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}