在使用MediaMuxer合并视频和音频流时,应该根据设备的不同设置正确的格式和参数。以下示例代码演示了如何正确设置MediaMuxer。
// 创建音频 MediaFormat audioFormat = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC, 44100, 1); audioFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC); audioFormat.setInteger(MediaFormat.KEY_BIT_RATE, 64000); audioFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 1024 * 64);
// 创建视频 MediaFormat videoFormat = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 720, 1280); videoFormat.setInteger(MediaFormat.KEY_PROFILE, MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline); videoFormat.setInteger(MediaFormat.KEY_BIT_RATE, 125000); videoFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 30); videoFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5); videoFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); videoFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 720 * 1280 * 3 / 2);
// 创建Muxer MediaMuxer muxer = new MediaMuxer(outputPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
// 添加音频和视频轨道 int audioTrackIndex = muxer.addTrack(audioFormat); int videoTrackIndex = muxer.addTrack(videoFormat);
// 开始 muxer.start();
// 写入音频和视频数据 muxer.writeSampleData(audioTrackIndex, audioBuffer, audioBufferInfo); muxer.writeSampleData(videoTrackIndex, videoBuffer, videoBufferInfo);
// 完成并释放 muxer.stop(); muxer.release();