import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class FFmpegUtil {
/**
* 合并视频和音频
* @param videoPath 视频文件路径
* @param audioPath 音频文件路径
* @param outputPath 合并后的视频文件输出路径
* @throws IOException
*/
public static void mergeVideoAndAudio(String videoPath, String audioPath, String outputPath) throws IOException {
// ffmpeg命令
List<String> command = new ArrayList<>();
command.add("ffmpeg");
command.add("-i");
command.add(videoPath);
command.add("-i");
command.add(audioPath);
command.add("-filter_complex");
command.add("[0:a]volume=0.5,apad[A];[1:a]volume=0.5[B];[A][B]amix=inputs=2:duration=first:dropout_transition=2");
command.add("-c:v");
command.add("copy");
command.add("-c:a");
command.add("aac");
command.add("-strict");
command.add("experimental");
command.add("-b:a");
command.add("192k");
command.add(outputPath);
ProcessBuilder builder = new ProcessBuilder();
builder.command(command);
builder.redirectErrorStream(true);
Process process = builder.start();
// 读取命令执行结果
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 关闭输入流
reader.close();
// 等待命令执行完成
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
这里使用ProcessBuilder来调用FFmpeg命令,合并视频和音频的命令与之前的命令相似,只是在音频合并的部分增加了音量减半的参数。在命令执行完成后,将命令输出打印到控制台。您可以根据需要修改命令,例如调整音频音量、音频码率等参数。调用该方法可以通过以下代码实现:
public static void main(String[] args) {
String videoPath = "video.mp4";
String audioPath = "audio.mp3";
String outputPath = "output.mp4";
try {
FFmpegUtil.mergeVideoAndAudio(videoPath, audioPath, outputPath);
} catch (IOException e) {
e.printStackTrace();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。