利用MediaMuxer将mp4中音视频分离需要用到的类有MediaExtractor,MediaFormat,以及主要的MediaMuxer.
MediaExtractor 主要是将mp4文件中的音视频Track抽出来以供MediaMuxer使用。例如:
MediaExtraor mediaExtraor=new MediaExtraor();
mVideoExtractor.setDataSource(inputFilePath);
for (int i = 0; i < mVideoExtractor.getTrackCount(); i++)
{ String mime = mVideoExtractor.getTrackFormat(i).getString(MediaFormat.KEY_MIME);
if (mime.startsWith("video/")){
//视频
mVideoFormat = mVideoExtractor.getTrackFormat(i);
int width = mVideoFormat.getInteger("width");
int height = mVideoFormat.getInteger("height");
video_frame_rate = mVideoFormat.getInteger(MediaFormat.KEY_FRAME_RATE);
long duration = mVideoFormat.getLong("durationUs");
//保存TrackIndex
indexVideo=i;
Log.i("Video", "width" + width + "\theight" + height + "\tduration" + duration + "\tvideo_frame_rate" + video_frame_rate + "\t" + mVideoFormat.toString()); // mVideoExtractor.selectTrack(indexVideo);
} else if (mime.startsWith("audio/")) {
//音频Track
}/
}
MeidaFormat 主要是一些存储一些音视频信息。例如:
//上面的粗体代码 = =
mVideoFormat = mVideoExtractor.getTrackFormat(i);
感兴趣的可以将获取到的MediaFormat对象toString()看看。
下面开始分离视频的主要代码
MediaMuxer muxers =null;
try {
//path 输出文件路径 format MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4
muxers =new MediaMuxer(path, format);
MediaFormat mediaFormat = mediaExtractor.getTrackFormat(indexVideo);
int video_frame_rate = mediaFormat.getInteger(MediaFormat.KEY_FRAME_RATE);
long size = mediaFormat.getLong("durationUs");
long sum =0;
mediaExtractor.selectTrack(indexVideo);
muxers.addTrack(mediaFormat);
if (muxers !=null) {
muxers.start();
if (indexVideo != -1) {
MediaCodec.BufferInfo info =new MediaCodec.BufferInfo();
info.presentationTimeUs =0;
ByteBuffer byteBuffer = ByteBuffer.allocate(100 *1024);
while (true) {
int sampleSize = mediaExtractor.readSampleData(byteBuffer, 0);
if (sampleSize <0) {
break;
}
//下一帧
mediaExtractor.advance();
info.offset =0;
info.size = sampleSize;
info.flags = MediaCodec.BUFFER_FLAG_SYNC_FRAME;
info.presentationTimeUs +=1000 *1000 / video_frame_rate;
muxers.writeSampleData(indexVideo, byteBuffer, info);
sum +=1000 *1000 / video_frame_rate;
if (listener !=null) {
//进度显示 用于回调呈现UI给用户
float present = (float) ((sum *100.0) / size);
listener.onProgress(present);
}
}
}
}
}catch (IOException e) {
e.printStackTrace();
if (listener !=null) {
listener.onFailure(e.getMessage());
}
}
// 释放MediaMuxer
muxers.stop();
muxers.release();
mediaExtractor.release();
网友评论