我需要在android上合并几个mp4文件,所以我尝试使用mp4parser合并几个mp4。
private void mergeMp4(File output, String[] files) throws IOException {
Movie[] inMovies = new Movie[files.length];
for (int i=0, len = files.length; i<len; ++i) {
inMovies[i] = MovieCreator.build("/tmp/tmp/" + files[i]);
}
List<Track> videoTracks = new LinkedList<Track>();
List<Track> audioTracks = new LinkedList<Track>();
for (Movie m : inMovies) {
for (Track t : m.getTracks()) {
if (t.getHandler().equals("soun")) {
audioTracks.add(t);
}
if (t.getHandler().equals("vide")) {
videoTracks.add(t);
}
}
}
Movie result = new Movie();
if (audioTracks.size() > 0) {
result.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
}
if (videoTracks.size() > 0) {
result.addTrack(new AppendTrack(videoTracks.toArray(new Track[videoTracks.size()])));
}
Container out = new DefaultMp4Builder().build(result);
FileChannel fc = new RandomAccessFile(output, "rw").getChannel();
out.writeContainer(fc);
fc.close();
}
// work correct for non-merged mp4 file
private long getDuration(String filename) throws IOException {
IsoFile isoFile = new IsoFile(filename);
long lengthInSeconds = isoFile.getMovieBox().getMovieHeaderBox().getDuration() / isoFile.getMovieBox().getMovieHeaderBox().getTimescale();
return lengthInSeconds * 1000;
}
代码中的某处
File tmp = new File("/tmp/tmp");
String[] tmpFiles = tmp.list();
File recordedFile = new File("/mnt/sdcard/app/output.mp4")
mergeMp4(recordedFile, tmpFiles);
// both print value near 0 (about 20 millis)
Log.d("TAG", String.valueOf(getDuration(recordedFile)));
System.out.println(getDuration(recordedFile));
如果我尝试使用Android MediaPlayer或任何其他播放器播放合并文件:
player = new MediaPlayer();
try {
player.setDataSource(getFilename());
player.prepare();
player.start();
int duration = player.getDuaration();
// both print value near 0 (about 20 millis)
Log.d("TAG", String.valueOf(duration));
System.out.println(duration);
} catch (IOException e) {
Log.e(TAG, "prepare() failed", e);
}
它是合并文件,但所有媒体播放器甚至mp4parser获取持续时间的作者的方法都返回该持续时间总是大约0(零)秒。