Java-使用FFmpeg进行音视频文件合并
目录
Java 使用FFmpeg进行音视频文件合并
FFmpeg实现音视频文件合并
最近需要用到将得到的音视频文件进行合并,查找资料发现FFmpeg是个非常不错的开源软件。简单几条命令行就能实现大用途。现将自己写的代码贴出来,以免再次翻找资料浪费时间。
我是做Java的,属刚入门,希望大家多批评指正,共同进步,谢谢。
关于FFmpeg的命令行,可以查看我的另一篇文档:http://zk461759809.iteye.com/admin/blogs/1636634
public boolean mergeFile(File file) {
//合并文件
//头一个file为amr文件
try {
log.info("Begin to merge video file " + videoFile.getAbsolutePath() + " into " + armFile.getAbsolutePath());
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if(classLoader == null) {
classLoader = ClassLoader.getSystemClassLoader();
}
//注意FFmpeg路径
String command =new File(classLoader.getResource("").toURI()).getParentFile() + "\\ffmpeg -i " + armFile.getAbsolutePath() + " -r 15 -i "
+ videoFile.getAbsolutePath() + " -vf \"transpose=1\" -c:a copy -c:v libx264 " + videoFile.getParentFile() + "\_" + videoFile.getName();
// System.out.println(command);
log.info("The command of ffmpeg is " + command);
Process process =Runtime.getRuntime().exec(command);
final InputStream in = process.getInputStream();
final InputStream error = process.getErrorStream();
//等待该进程结束后在执行后面操作
new Thread(){
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(error));
try {
while(br.readLine() != null) {
continue;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}.start();
//waitFor()操作阻塞线程,等待process执行结束
process.waitFor();
process.destroy();
log.info("Success to execute " + command);
log.info("Success to merge " + videoFile.getAbsolutePath() + " into " + armFile.getAbsolutePath() + ", and success to create " + videoFile.getParentFile() + "/_" + videoFile.getName());
} catch (Exception e) {
log.error("Exception occurs when merging video file", e);
return false;
}
return true;
}