user1318194
user1318194

Reputation:

Change a video's soundtrack to an audio file of the same length

I have two variables, Uri audioUri and Uri videoUri which point to the location of an audio file (any format the user has) and a video file (mp4) respectively. The video and audio are the same length.

I would like to create a video file that has the same video/frames as the video file, but uses the audio file as the soundtrack.

Upvotes: 1

Views: 1260

Answers (1)

user1318194
user1318194

Reputation:

I ended up using the mp4parser library. The MediaExtractor and MediaMuxer classes were introduced in API 16 and 18 respectively so they are too new for my project.

The caveat of this method is that at the time of writing the audio source must be an aac or mp3 file and the video file must be an mp4 file.

Using Android Studio and Gradle, you can install and use it like this:

Open Gradle Scripts -> build.gradle (Module: app) and add to the end of the dependencies block

compile 'com.googlecode.mp4parser:isoparser:1.0.+'

Click the "Sync Now" button in the yellow banner that appears after you make this change.

Now in your Java file write:

try
{
    H264TrackImpl h264Track = new H264TrackImpl(new FileDataSourceImpl(videoFile);
    MP3TrackImpl mp3Track = new MP3TrackImpl(new FileDataSourceImpl(audioFile);
    Movie movie = new Movie();
    movie.addTrack(h264Track);
    movie.addTrack(mp3Track);
    Container mp4file = new DefaultMp4Builder().build(movie);
    FileChannel fileChannel = new FileOutputStream(new File(outputFile)).getChannel();
    mp4file.writeContainer(fileChannel);
    fileChannel.close();
}
catch (Exception e)
{
    Toast.makeText(this, "An error occurred: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}

Use the Alt+Enter tool to have all the classes imported. There were multiple choices for the Movie class for me, so make sure to choose the one starting with com.googlecode.mp4parser.

It is left to you to handle exceptions and to define the self-explanatory Strings outputFile, audioFile and videoFile.

Upvotes: 2

Related Questions