Search code examples
androidmp4

How to add audio to an existing video without creating a new video in Android


I want to make a dubbing app. I will get audio from user's microphone. I have a mp4 video. I want to override user's audio to mp4 video. How can i do this?
I searched a lot and i think mp4 parser library will help me but it is very hard to understand me.
I didn't find a good example for this.
Is there anyone to explain to me clearly?


Solution

  • if your MP4 has been encoded by h.264 , you can easily use MP4parser.

    try {
    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    H264TrackImpl h264Track = new H264TrackImpl(new FileDataSourceImpl(baseDir + "/video.h264"));
    AACTrackImpl aacTrack = new AACTrackImpl(new FileDataSourceImpl( baseDir + "/aac_sample.aac" ));
    
    Movie movie = new Movie();
    movie.addTrack(h264Track);
    movie.addTrack(aacTrack);
    Container mp4file = new DefaultMp4Builder().build(movie);
    
    FileChannel fc = new FileOutputStream(new File(baseDir +"/output.mp4")).getChannel();
    mp4file.writeContainer(fc);
    fc.close();
    
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      } catch (IOException e) {
       e.printStackTrace();
    }
    

    Not Tested. May it help.