importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.util.ArrayList;importjava.util.List;public classMergeVideoMp4 {privateString ffmpegEXE;publicMergeVideoMp4(String ffmpegEXE) {super();this.ffmpegEXE =ffmpegEXE;
}public voidconvertor(String videoInputPath, String videoTmpPath, String mp3InputPath,double seconds, String videoOutputPath) throwsException {//去除视屏背景音乐 ffmpeg.exe -i 吃鸡.mp4 -vcodec copy -an 吃鸡1.mp4
List command = new ArrayList<>();
command.add(ffmpegEXE);
command.add("-i");//输入
command.add(videoInputPath);
command.add("-vcodec");//分离视屏 分离音频:-acodec copy -vn
command.add("copy");
command.add("-an"); //去掉音频
command.add(videoTmpPath);for(String c : command) {
System.out.print(c+ " ");
}this.processed(command);//合成去除背景音乐的视屏和mp3文件 ffmpeg.exe -i 吃鸡1.mp4 -i 小太阳.mp3 -t 10 -y result.mp4
List command2 = new ArrayList<>();
command2.add(ffmpegEXE);
command2.add("-i");
command2.add(videoTmpPath);
command2.add("-i");
command2.add(mp3InputPath);
command2.add("-t"); //指定视屏时间
command2.add(String.valueOf(seconds));
command2.add("-y"); //当已存在输出文件时,不提示是否覆盖
command2.add(videoOutputPath);
System.out.println();for(String c : command2) {
System.out.print(c+ " ");
}this.processed(command2);
}/*** 执行FFmpeg命令
*@paramcommand
*@throwsIOException*/
private void processed(Listcommand){
ProcessBuilder builder= newProcessBuilder(command);
Process process;
InputStream errorStream= null;
InputStreamReader inputStreamReader= null;
BufferedReader br= null;try{
process=builder.start();
errorStream=process.getErrorStream();
inputStreamReader= newInputStreamReader(errorStream);
br= newBufferedReader(inputStreamReader);
String line= "";while ( (line = br.readLine()) != null) {
}
}catch(IOException e) {
e.printStackTrace();
}finally{try{if (br != null) {
br.close();
}if (inputStreamReader != null) {
inputStreamReader.close();
}if (errorStream != null) {
errorStream.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}public static voidmain(String[] args) {
MergeVideoMp4 ffmpeg= new MergeVideoMp4("C:\\ffmpeg\\bin\\ffmpeg.exe");try{
ffmpeg.convertor("D:\\吃鸡(0).mp4", "D:\\吃鸡.mp4","D:\\小太阳.mp3", 7.1, "D:\\这是通过java生产的视频.mp4");
}catch(Exception e) {
e.printStackTrace();
}
}
}