将MP3音频文件和MP4电影相结合

2022-04-08 00:00:00 mp4 mp3 java xuggler

使用Java和XGUGER-以下代码将MP3音频文件和MP4电影文件组合在一起,并输出组合的MP4文件。

我希望输出视频的持续时间等于输入视频文件的持续时间

如果我将循环条件设置为:

while (containerVideo.readNextPacket(packetvideo) >= 0) 

它进行了400次迭代--使电影播放了15秒。就是我想要的。

但由于某种原因,音频在10秒后被切断-使电影的最后5秒静音。

看起来视频IStreamCoder的单次迭代的时长与音频IStreamCoder的单次迭代的时长不同。

如何才能让声音填满电影的整个15秒?

    String inputVideoFilePath = "in.mp4";
    String inputAudioFilePath = "in.mp3";
    String outputVideoFilePath = "out.mp4";

    IMediaWriter mWriter = ToolFactory.makeWriter(outputVideoFilePath);

    IContainer containerVideo = IContainer.make();
    IContainer containerAudio = IContainer.make();

    // check files are readable
    if (containerVideo.open(inputVideoFilePath, IContainer.Type.READ, null) < 0)
        throw new IllegalArgumentException("Cant find " + inputVideoFilePath);
    if (containerAudio.open(inputAudioFilePath, IContainer.Type.READ, null) < 0)
        throw new IllegalArgumentException("Cant find " + inputAudioFilePath);

    // read video file and create stream
    IStreamCoder coderVideo = containerVideo.getStream(0).getStreamCoder();
    if (coderVideo.open(null, null) < 0)
        throw new RuntimeException("Cant open video coder");
    IPacket packetvideo = IPacket.make();
    int width = coderVideo.getWidth();
    int height = coderVideo.getHeight();

    // read audio file and create stream
    IStreamCoder coderAudio = containerAudio.getStream(0).getStreamCoder();
    if (coderAudio.open(null, null) < 0)
        throw new RuntimeException("Cant open audio coder");
    IPacket packetaudio = IPacket.make();

    mWriter.addAudioStream(1, 0, coderAudio.getChannels(), coderAudio.getSampleRate());
    mWriter.addVideoStream(0, 0, width, height);

    while (containerVideo.readNextPacket(packetvideo) >= 0) {

        containerAudio.readNextPacket(packetaudio);

        // video packet
        IVideoPicture picture = IVideoPicture.make(coderVideo.getPixelType(), width, height);
        coderVideo.decodeVideo(picture, packetvideo, 0);
        if (picture.isComplete()) 
            mWriter.encodeVideo(0, picture);

        // audio packet 
        IAudioSamples samples = IAudioSamples.make(512, coderAudio.getChannels(), IAudioSamples.Format.FMT_S32);
        coderAudio.decodeAudio(samples, packetaudio, 0);
        if (samples.isComplete()) 
            mWriter.encodeAudio(1, samples);

    }

    coderAudio.close();
    coderVideo.close();
    containerAudio.close();
    containerVideo.close();
    mWriter.close();

解决方案

代码不错。谢谢。要捕获剩余的音频,请在末尾添加一个循环来读取音频包,直到没有更多的音频包。

    while (samples.isComplete() ) {
        containerAudio.readNextPacket(packetaudio);
        coderAudio.decodeAudio(samples, packetaudio, 0);
        writer.encodeAudio(iAudioStream, samples);
        Utility.console(String.format("%s %d", Utility.timeStamp(),
            samples.getPts() ));            
    }

相关文章