在Android中将音频文件与捕获的视频合并

时间:2015-04-06 15:49:28

标签: android audio video

是否可以将音频和视频文件合并为单个文件。我的 要求是:一个可以录制视频的android应用程序(mp4),然后我的本地文件夹中有一些音频文件(mp3),我想将它添加到通过camcoder捕获的视频中。因此,最终效果将像播放视频一样,并且将听到添加的音频,这些音频将在内部合并。我该怎么做? 附:合并必须在内部完成.Camcorder不会录制任何音频。

请帮忙

1 个答案:

答案 0 :(得分:1)

我无法通过使用mp3文件取得成功。相反,我使用mp4文件作为背景音频。如果您有兴趣处理mp4文件,下面的代码片段可以帮助您

String root = Environment.getExternalStorageDirectory().toString();
            String audio = root +"/test.mp4";
            String video = root +"/myvideo.mp4";
            String output = root+ "/ouputVideo.mp4";
            Log.e("FILE", "audio:"+audio + " video:"+video+ " out:"+output);
            mux(video, audio, output);



public boolean mux(String videoFile, String audioFile, String outputFile) {
    Movie video;
    try {
        video = new MovieCreator().build(videoFile);
    } catch (RuntimeException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    Movie audio;

    try {
        audio = new MovieCreator().build(audioFile);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (NullPointerException e) {

        e.printStackTrace();
        return false;
    }

    Track audioTrack = audio.getTracks().get(1);

    //video.getTracks().remove(1);
    video.addTrack(audioTrack);

    Container out = new DefaultMp4Builder().build(video);

    FileOutputStream fos;
    try {
        fos = new FileOutputStream(outputFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    }
    BufferedWritableFileByteChannel byteBufferByteChannel = new BufferedWritableFileByteChannel(fos);
    try {
        out.writeContainer(byteBufferByteChannel);
        byteBufferByteChannel.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}