3

我需要合并音频(aac 格式)和视频(mp4 格式)。我为此使用 mp4parser 库。

public static boolean mergeMP4withAAC(String videoFilePath, String audioFilePath, String outFilePath) {
    try {
        /* Load a MP4 file as movie */
        Movie movieVideo = MovieCreator.build(videoFilePath);

        /* Fetch needed audio track and video track from MP4 file */
        Track audioTrack = new AACTrackImpl(new FileDataSourceImpl(audioFilePath));
        Track videoTrack = movieVideo.getTracks().get(0);

        double t1 = 1.0 * videoTrack.getDuration() / videoTrack.getTrackMetaData().getTimescale();
        double t2 = 1.0 * audioTrack.getDuration() / audioTrack.getTrackMetaData().getTimescale();
        Log.d(TAG, t1 + " " + t2);

        double factor = (t1 * audioTrack.getTrackMetaData().getTimescale()) / audioTrack.getDuration();
        Log.d(TAG, "factor = " + factor);

        /* Construct a movie */
        Movie movie = new Movie();
        if (factor < 1.0) {
            long trackSize = audioTrack.getSamples().size();
            long sampleNeeded = (long) (trackSize * factor);

            Log.d(TAG, (trackSize - sampleNeeded - 1) + " " + trackSize);

            movie.addTrack(videoTrack);
            movie.addTrack(new CroppedTrack(audioTrack, trackSize - sampleNeeded - 1, trackSize));
        } else {
            Log.d(TAG, "mergeMP4withAAC 1");
            long trackSize = videoTrack.getSamples().size();
            long sampleNeeded = (long) (trackSize / factor);
            movie.addTrack(new CroppedTrack(videoTrack, trackSize - sampleNeeded - 1, trackSize));
            Log.d(TAG, "mergeMP4withAAC 2");
            movie.addTrack(audioTrack);
            Log.d(TAG, "mergeMP4withAAC 3");
        }

        /* Build it */
        Container mp4file = new DefaultMp4Builder().build(movie);
        Log.d(TAG, "mergeMP4withAAC 4");
        /* Write resulted MP4 to file */
        FileChannel fc = new FileOutputStream(new File(outFilePath)).getChannel();
        Log.d(TAG, "mergeMP4withAAC 5 " + mp4file.getBoxes().size());
        mp4file.writeContainer(fc); // the problem I guess may be here
        Log.d(TAG, "mergeMP4withAAC 6");
        fc.close();
        Log.d(TAG, "mergeMP4withAAC 7");
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

但是当我生成的视频文件超过 5-6 分钟时,一些设备停止工作(这意味着 UI 被冻结,用户无能为力,但 Android 不显示任何消息,恢复应用程序的唯一方法是重启设备)。

正如您在代码片段中看到的那样,我已经记录了每一行,我发现问题出在我将结果文件写入磁盘的一行中。

我还在不同的设备上对其进行了测试。Moto G (1gen)、Moto G(2gen) (Android 5.0.2) 和 Nexus 5 (Android 5.1.1) 无法合并文件超过 5-6 分钟,但 Nexus 7 (Android 5.1.1) 可以合并文件超过 10 分钟。

那么有人可以向我解释一下这个问题或给出一些建议或例子。非常感谢。

4

0 回答 0