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();    }}