代码描述
一下代码是部分代码,仅作展示。场景为将指定路径的视频文件转为统一格式,然后将转化后的文件覆盖掉原本的文件。
List<String> commandList = new ArrayList<>();
commandList.add("cmd");
commandList.add("/c");
commandList.add("ffmpeg -i "+ mp4FilePath +" -c:v h264 -c:a aac -strict -2 -y "+ tempFilePath +" && move /y "+ tempFilePath + " " + mp4FilePath);
ProcessBuilder pb = new ProcessBuilder(commandList);
pb.redirectErrorStream(true);
logger.info("视频编码格式化准备命令:" + "ffmpeg -i "+ mp4FilePath +" -c:v h264 -c:a aac -strict -2 -y "+ tempFilePath +" && move /y "+ tempFilePath + " " + mp4FilePath);
logger.info("视频编码格式化开始执行");
try {
process = pb.start();
process.waitFor();
} catch (Exception e) {
logger.info("视频编码格式化异常:FFmpeg命令报错" + JSON.toJSONString(e));
try{
if (process != null) {
process.getErrorStream().close();
process.getInputStream().close();
process.getOutputStream().close();
}
}
catch(Exception ee){}
return false;
}
logger.info("视频编码格式化执行完成");
结果发现在process.waitFor();
这里卡住不往下执行,通过查阅各位前辈的文章,总结出两种方法。
方法一:设置ffmpeg进程不向窗口写入数据,也就是不打印日志
将上面的ffmpeg
命令
"ffmpeg -i "+ mp4FilePath +" -c:v h264 -c:a aac -strict -2 -y "+ tempFilePath +" && move /y "+ tempFilePath + " " + mp4FilePath);
改为,就是加了-loglevel quiet
"ffmpeg -loglevel quiet -i "+ mp4FilePath +" -c:v h264 -c:a aac -strict -2 -y "+ tempFilePath +" && move /y "+ tempFilePath + " " + mp4FilePath);
方法二:将ffmpeg的日志逐行打印出来,打印完了就结束了
增加了获取输出流
以及读取输出信息
的代码,结束后就完成了。
List<String> commandList = new ArrayList<>();
commandList.add("cmd");
commandList.add("/c");
commandList.add("ffmpeg -i "+ mp4FilePath +" -c:v h264 -c:a aac -strict -2 -y "+ tempFilePath +" && move /y "+ tempFilePath + " " + mp4FilePath);
ProcessBuilder pb = new ProcessBuilder(commandList);
pb.redirectErrorStream(true);
logger.info("视频编码格式化准备命令:" + "ffmpeg -i "+ mp4FilePath +" -c:v h264 -c:a aac -strict -2 -y "+ tempFilePath +" && move /y "+ tempFilePath + " " + mp4FilePath);
try {
process = pb.start();
} catch (Exception e) {
logger.info("视频编码格式化异常:FFmpeg命令报错" + JSON.toJSONString(e));
try{
if (process != null) {
process.getErrorStream().close();
process.getInputStream().close();
process.getOutputStream().close();
}
}
catch(Exception ee){}
return false;
}
logger.info("视频编码格式化开始执行");
// 获取输出流
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
// 读取输出信息
String line;
while (true) {
try {
if ((line = br.readLine()) == null) break;
} catch (IOException e) {
logger.info("视频编码格式化异常:FFmpeg读取输出信息报错" + JSON.toJSONString(e));
return false;
}
// System.out.println(line);
}
try {
is.close();
isr.close();
br.close();
} catch (IOException e) {
logger.info("视频编码格式化异常:关闭流报错" + JSON.toJSONString(e));
return false;
}
logger.info("视频编码格式化执行完成");