int videoTrackIndex = -1;
int audioTrackIndex = -1;
for(int i = 0; i < mMediaExtractor.getTrackCount(); i++) {
//获取码流的详细格式/配置信息
MediaFormat format = mMediaExtractor.getTrackFormat(i);
String mime = format.getString(MediaFormat.KEY_MIME);
if(mime.startsWith("video/")) {
videoTrackIndex = i;
}
else if(mime.startsWith("audio/")) {
audioTrackIndex = i;
}
....
}
获取到媒体文件的详细信息之后,就可以选择指定的通道,并分离和读取数据了:
mMediaExtractor.selectTrack(videoTrackIndex); //选择读取视频数据
while(true) {
int sampleSize = mMediaExtractor.readSampleData(buffer, 0); //读取一帧数据
if(sampleSize < 0) {
break;
}
mMediaExtractor.advance(); //移动到下一帧
}
mMediaExtractor.release(); //读取结束后,要记得释放资源
public MediaMuxer(String path, int format);
创建对象之后,一个比较重要的操作就是addTrack(),添加数据通道,该函数需要传入MediaFormat对象,MediaFormat即媒体格式类,用于描述媒体的格式参数,如视频帧率、音频采样率等。
MediaFormat format = MediaFormat.createVideoFormat("video/avc",320,240);
注意,这里有一个比较大的坑,就是,如果手动创建MediaFormat对象的话,一定要记得设置"csd-0"和"csd-1"这两个参数:
byte[] csd0 = {x,x,x,x,x,x,x...}
byte[] csd1 = {x,x,x,x,x,x,x...}
format.setByteBuffer("csd-0",ByteBuffer.wrap(csd0));
format.setByteBuffer("csd-1",ByteBuffer.wrap(csd1));
BufferInfo info = new BufferInfo();
info.offset = 0;
info.size = sampleSize;
info.flags = MediaCodec.BUFFER_FLAG_SYNC_FRAME;
info.presentationTimeUs = timestamp;
mMediaMuxer.stop();
mMediaMuxer.release();
protected boolean process() throws IOException {
mMediaExtractor = new MediaExtractor();
mMediaExtractor.setDataSource(SDCARD_PATH+"/input.mp4");
int mVideoTrackIndex = -1;
int framerate = 0;
for(int i = 0; i < mMediaExtractor.getTrackCount(); i++) {
MediaFormat format = mMediaExtractor.getTrackFormat(i);
String mime = format.getString(MediaFormat.KEY_MIME);
if(!mime.startsWith("video/")) {
continue;
}
framerate = format.getInteger(MediaFormat.KEY_FRAME_RATE);
mMediaExtractor.selectTrack(i);
mMediaMuxer = new MediaMuxer(SDCARD_PATH+"/ouput.mp4", OutputFormat.MUXER_OUTPUT_MPEG_4);
mVideoTrackIndex = mMediaMuxer.addTrack(format);
mMediaMuxer.start();
}
if(mMediaMuxer == null) {
return false;
}
BufferInfo info = new BufferInfo();
info.presentationTimeUs = 0;
ByteBuffer buffer = ByteBuffer.allocate(500*1024);
while(true) {
int sampleSize = mMediaExtractor.readSampleData(buffer, 0);
if(sampleSize < 0) {
break;
}
mMediaExtractor.advance();
info.offset = 0;
info.size = sampleSize;
info.flags = MediaCodec.BUFFER_FLAG_SYNC_FRAME;
info.presentationTimeUs += 1000*1000/framerate;
mMediaMuxer.writeSampleData(mVideoTrackIndex,buffer,info);
}
mMediaExtractor.release();
mMediaMuxer.stop();
mMediaMuxer.release();
return true;
}