如何在Java中合并音频和视频

时间:2012-08-04 18:48:18

标签: java audio video add xuggler

我们创建了一个使用Xuggler记录网络摄像头流的应用程序,但视频和音频是分开的。

我们需要合并而不是连接这两个文件。

如何在Java中完成?

5 个答案:

答案 0 :(得分:4)

如果你有音频和视频文件,那么你可以使用FFmpeg将它们合并到一个音频视频文件中:

  1. 下载FFmpeg:http://ffmpeg.zeranoe.com/builds/
  2. 将下载的文件解压缩到特定文件夹,例如c:\ ffmpeffolder
  3. 使用cmd移动到特定文件夹c:\ ffmpeffolder \ bin
  4. 运行以下命令:$ ffmpeg -i audioInput.mp3 -i videoInput.avi -acodec copy -vcodec copy outputFile.avi 就是这个。 outputFile.avi将是生成的文件。

答案 1 :(得分:2)

您可以使用Java调用ffmpeg,如下所示:

public class WrapperExe {

 public boolean doSomething() {

 String[] exeCmd = new String[]{"ffmpeg", "-i", "audioInput.mp3", "-i", "videoInput.avi" ,"-acodec", "copy", "-vcodec", "copy", "outputFile.avi"};

 ProcessBuilder pb = new ProcessBuilder(exeCmd);
 boolean exeCmdStatus = executeCMD(pb);

 return exeCmdStatus;
} //End doSomething Function

private boolean executeCMD(ProcessBuilder pb)
{
 pb.redirectErrorStream(true);
 Process p = null;

 try {
  p = pb.start();

 } catch (Exception ex) {
 ex.printStackTrace();
 System.out.println("oops");
 p.destroy();
 return false;
}
// wait until the process is done
try {
 p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("woopsy");
p.destroy();
return false;
}
return true;
 }// End function executeCMD
} // End class WrapperExe

答案 2 :(得分:1)

答案 3 :(得分:0)

取决于格式,您可以使用JMF,Java Media Framework,这是古老而且从未如此出色,但可能对您的目的而言足够好。

如果它不支持您的格式,您可以使用FFMPEG包装器,如果我正确记住,它提供JMF接口但使用FFMPEG:http://fmj-sf.net/ffmpeg-java/getting_started.php

答案 4 :(得分:0)

正如其他答案已经建议的那样,ffmeg似乎是这里的最佳解决方案。

这是我最后得到的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;

public static File mergeAudioToVideo(
        File ffmpegExecutable,  // ffmpeg/bin/ffmpeg.exe
        File audioFile,
        File videoFile,
        File outputDir,
        String outFileName) throws IOException, InterruptedException {

    for (File f : Arrays.asList(ffmpegExecutable, audioFile, videoFile, outputDir)) {
        if (! f.exists()) {
            throw new FileNotFoundException(f.getAbsolutePath());
        }
    }

    File mergedFile = Paths.get(outputDir.getAbsolutePath(), outFileName).toFile();
    if (mergedFile.exists()) {
        mergedFile.delete();
    }

    ProcessBuilder pb = new ProcessBuilder(
            ffmpegExecutable.getAbsolutePath(),
            "-i",
            audioFile.getAbsolutePath(),
            "-i",
            videoFile.getAbsolutePath() ,
            "-acodec",
            "copy",
            "-vcodec",
            "copy",
            mergedFile.getAbsolutePath()
    );
    pb.redirectErrorStream(true);
    Process process = pb.start();
    process.waitFor();

    if (!mergedFile.exists()) {
        return null;
    }
    return mergedFile;
}
相关问题