How to multiplex mp3 and mp4 files in Android

2019-04-02 19:46发布

问题:

Problem statement: I am designing an android app in which I have to get images from the user's gallery, combine them to make a video file and add background music. I have used jcodec library to create mp4 video file using my image resources (I know how to get images from gallery and show them in ImageViews and create bitmaps from them). I have a mp4 file. Now, I want to add background music in it using a mp3 file.

Please can anybody help me with this? I cannot add it using jcodec or atleast I don't know how to do that. I can use any library that can do this job but it should be in Java because I don't want to use ndk. I tried ffmpeg and opencv for java but it increased the size of my app by more than 15MB and jcodec has already done half job of making a mp4 file.

I can give you the code that I used to make mp4 file. Thanks in advance.

回答1:

I think JCODEC not support add mp3 in MP4.But JAVACV Support add mp3 in mp4.

download JAVACV from this link https://github.com/bytedeco/javacv.

this library support Create video from Images and also add mp3 in mp4.

code for add mp3 in mp4.

Note: it's may not work for create mp4 from JCODEC, create mp4 using JAVACV

FrameGrabber grabber1 = new FFmpegFrameGrabber(videoPath);
            FrameGrabber grabber2 = new FFmpegFrameGrabber(audioPath);
            grabber1.start();
            grabber2.start();
            FrameRecorder recorder = new FFmpegFrameRecorder(OutputPath,
                    grabber1.getImageWidth(), grabber1.getImageHeight(), 2);
            recorder.setFormat("mp4");
            recorder.setVideoQuality(1);
            recorder.setFrameRate(grabber1.getFrameRate());
            recorder.setSampleRate(grabber2.getSampleRate());
            recorder.start();
            Frame frame1, frame2 = null;
            long timestamp = -2;
            int count = 0;
            boolean isFirstTime = false;
            boolean isFirstCheck = true;
            while ((frame1 = grabber1.grabFrame())!=null) {
                //frame1 = grabber1.grabFrame();
                frame2 = grabber2.grabFrame();
                recorder.record(frame1);
                recorder.record(frame2);

                }
            recorder.stop();
            grabber1.stop();
            grabber2.stop();
    } catch (org.bytedeco.javacv.FrameGrabber.Exception e) {
            e.printStackTrace();
        } catch (Exception e1) {

        }