目標,將MP3中的聲音合成到MP4中去。
采用的第三方庫:MP4Parser,
Muxing Audio/Video
The API and the process is straight-forward:
-
You wrap each raw format file into an appropriate Track object.
H264TrackImpl h264Track = new H264TrackImpl(new FileDataSourceImpl("video.h264")); AACTrackImpl aacTrack = new AACTrackImpl(new FileDataSourceImpl("audio.aac"));
-
These Track object are then added to a Movie object
Movie movie = new Movie(); movie.addTrack(h264Track); movie.addTrack(aacTrack);
-
The Movie object is fed into an MP4Builder to create the container.
Container mp4file = new DefaultMp4Builder().build(movie);
-
Write the container to an appropriate sink.
FileChannel fc = new FileOutputStream(new File("output.mp4")).getChannel(); mp4file.writeContainer(fc); fc.close();
要求.h264文件和aac文件的作為“輸入”, 輸出為mp4格式。
測試:使用MediaRecorder生成后綴為.H264的文件。測試可以在手機端播放。使用以上方法與一個aac文件合成。報錯:
java.lang.NullPointerException: Attempt to read from field 'int com.googlecode.mp4parser.h264.model.PictureParameterSet.seq_parameter_set_id' on a null object reference
h264Track = new H264TrackImpl(new FileDataSourceImpl("/storage/emulated/0/DCIM/TestCamera/VID_2016.H264"));//報錯行
構造失敗。谷歌該問題無果。
查看mp4parser的issues:
Combine a music.m4a on a video.mp4 overwrite my video audio
mp4parser的作者回復:
“Basically you want to merge two audio tracks to one. Players won't play two audio tracks at the same time. This is a use case that requires decoding, then merging and encoding into one audio track again. The MP4parser cannot do that. I guess you'll need to use ffmpeg or the MediaCodec API.”
一句話,mp4parser做不到。