Android音视频之MediaCodec和MediaMuxer使用

一、MediaCodec介绍
Android中可以使用MediaCodec来访问底层的媒体编解码器,可以对媒体进行编/解码。

MediaCodec可以处理的数据有以下三种类型:压缩数据、原始音频数据、原始视频数据。这三种类型的数据均可以利用ByteBuffers进行处理,但是对于原始视频数据应提供一个Surface以提高编解码器的性能。Surface直接使用native视频数据缓存,而没有映射或复制它们到ByteBuffers,因此,这种方式会更加高效。

MediaCodec采用异步方式处理数据,并且使用了一组输入输出缓存
(ByteBuffer)。通过请求一个空的输入缓存(ByteBuffer),向其中填充满数据并将它传递给编解码器处理。编解码器处理完这些数据并将处理结果输出至一个空的输出缓存(ByteBuffer)中。使用完输出缓存的数据之后,将其释放回编解码器:
在这里插入图片描述
MediaCodec的生命周期有三种状态:停止态-Stopped、执行态-Executing、释放态-Released,停止状态(Stopped)包括了三种子状态:未初始化(Uninitialized)、配置(Configured)、错误(Error)。执行状态(Executing)会经历三种子状态:刷新(Flushed)、运行(Running)、流结束(End-of-Stream)
在这里插入图片描述

  1. 当创建了一个MediaCodec对象,此时MediaCodec处于Uninitialized状态。首先,需要使用configure(…)方法对MediaCodec进行配置,这时MediaCodec转为Configured状态。然后调用start()方法使其转入Executing状态。在Executing状态可以通过上述的缓存队列操作处理数据。
  2. Executing状态包含三个子状态: Flushed、 Running 以及End-of-Stream。在调用start()方法后MediaCodec立即进入Flushed子状态,此时MediaCodec会拥有所有的缓存。一旦第一个输入缓存(input buffer)被移出队列,MediaCodec就转入Running子状态,这种状态占据了MediaCodec的大部分生命周期。当你将一个带有end-of-stream marker标记的输入缓存入队列时,MediaCodec将转入End-of-Stream子状态。在这种状态下,MediaCodec不再接收之后的输入缓存,但它仍然产生输出缓存直到end-of- stream标记输出。你可以在Executing状态的任何时候通过调用flush()方法返回到Flushed子状态。
  3. 通过调用stop()方法使MediaCodec返回到Uninitialized状态,因此这个MediaCodec可以再次重新配置 。当使用完MediaCodec后,必须调用release()方法释放其资源。
  4. 在极少情况下MediaCodec会遇到错误并进入Error状态。这个错误可能是在队列操作时返回一个错误的值或者有时候产生了一个异常导致的。通过调用 reset()方法使MediaCodec再次可用。你可以在任何状态调用reset()方法使MediaCodec返回到Uninitialized状态。否则,调用 release()方法进入最终的Released状态。

以编码音频为例:

final MediaFormat audioFormat = MediaFormat.createAudioFormat(MIME_TYPE, SAMPLE_RATE, 1);
audioFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
audioFormat.setInteger(MediaFormat.KEY_CHANNEL_MASK, AudioFormat.CHANNEL_IN_MONO);
audioFormat.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE);
audioFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
//audioFormat.setLong(MediaFormat.KEY_MAX_INPUT_SIZE, inputFile.length());
//audioFormat.setLong(MediaFormat.KEY_DURATION, (long)durationInMs );
if (DEBUG) Log.i(TAG, "format: " + audioFormat);
mMediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
mMediaCodec.configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mMediaCodec.start();

createDecoderBy…和createEncoderBy…,分别对应解码器和编码器。
调用configure(…)方法对MediaCodec进行配置,此时MediaCodec处于Configured状态。
接着调用MediaCodec的start()方法,此时MediaCodec处于Executing状态,可以通过getInputBuffers()方法和getOutputBuffers()方法获取缓存队列:

mAudioInputBuffers = mMediaCodec.getInputBuffers();
mAudioOutputBuffers = mMediaCodec.getOutputBuffers();

AudioVideoRecordingDemo的部分代码为例:
以下该图是编码每一帧音频数据的代码,取出mMediaCodec的inputbuffers数组,dequeueInputBuffer()方法是取出一个inputBuffer的地址index,然后put放入入参buffer。接下来判断length是否为0,不为0则是放入音频的数据,为0放入的是EndOfStream的帧,表示之后没有了数据会放入进来了。
在这里插入图片描述

 protected void drain() {
		Log.d(TAG, "drain:  mMediaCodec == null  " + (mMediaCodec == null));
    	if (mMediaCodec == null) return;
        ByteBuffer[] encoderOutputBuffers = mMediaCodec.getOutputBuffers();
        int encoderStatus, count = 0;
        final MediaMuxerWrapper muxer = mWeakMuxer.get();
        if (muxer == null) {
//        	throw new NullPointerException("muxer is unexpectedly null");
        	Log.w(TAG, "muxer is unexpectedly null");
        	return;
        }
LOOP:	while (mIsCapturing) {
			// get encoded data with maximum timeout duration of TIMEOUT_USEC(=10[msec])
            encoderStatus = mMediaCodec.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC);
	Log.d(TAG, "drain:  encoderStatus  " + encoderStatus);
            if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
                // wait 5 counts(=TIMEOUT_USEC x 5 = 50msec) until data/EOS come
                if (!mIsEOS) {
                	if (++count > 5)
                		break LOOP;		// out of while
                }
            } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
            	if (DEBUG) Log.v(TAG, "INFO_OUTPUT_BUFFERS_CHANGED");
                // this shoud not come when encoding
                encoderOutputBuffers = mMediaCodec.getOutputBuffers();
            } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
            	if (DEBUG) Log.v(TAG, "INFO_OUTPUT_FORMAT_CHANGED");
            	// this status indicate the output format of codec is changed
                // this should come only once before actual encoded data
            	// but this status never come on Android4.3 or less
            	// and in that case, you should treat when MediaCodec.BUFFER_FLAG_CODEC_CONFIG come.
                if (mMuxerStarted) {	// second time request is error
                    throw new RuntimeException("format changed twice");
                }
				// get output format from codec and pass them to muxer
				// getOutputFormat should be called after INFO_OUTPUT_FORMAT_CHANGED otherwise crash.
                final MediaFormat format = mMediaCodec.getOutputFormat(); // API >= 16
               	mTrackIndex = muxer.addTrack(format);
               	mMuxerStarted = true;
               	if (!muxer.start()) {
               		// we should wait until muxer is ready
               		synchronized (muxer) {
	               		while (!muxer.isStarted())
						try {
							muxer.wait(100);
						} catch (final InterruptedException e) {
							break LOOP;
						}
               		}
               	}
            } else if (encoderStatus < 0) {
            	// unexpected status
            	if (DEBUG) Log.w(TAG, "drain:unexpected result from encoder#dequeueOutputBuffer: " + encoderStatus);
            } else {
                final ByteBuffer encodedData = encoderOutputBuffers[encoderStatus];
                if (encodedData == null) {
                	// this never should come...may be a MediaCodec internal error
                    throw new RuntimeException("encoderOutputBuffer " + encoderStatus + " was null");
                }
                if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
                	// You shoud set output format to muxer here when you target Android4.3 or less
                	// but MediaCodec#getOutputFormat can not call here(because INFO_OUTPUT_FORMAT_CHANGED don't come yet)
                	// therefor we should expand and prepare output format from buffer data.
                	// This sample is for API>=18(>=Android 4.3), just ignore this flag here
					if (DEBUG) Log.d(TAG, "drain:BUFFER_FLAG_CODEC_CONFIG");
					mBufferInfo.size = 0;
                }

                if (mBufferInfo.size != 0) {
                	// encoded data is ready, clear waiting counter
            		count = 0;
                    if (!mMuxerStarted) {
                    	// muxer is not ready...this will prrograming failure.
                        throw new RuntimeException("drain:muxer hasn't started");
                    }
                    // write encoded data to muxer(need to adjust presentationTimeUs.
                   	mBufferInfo.presentationTimeUs = getPTSUs();
                   	muxer.writeSampleData(mTrackIndex, encodedData, mBufferInfo);
					prevOutputPTSUs = mBufferInfo.presentationTimeUs;
                }
                // return buffer to encoder
                mMediaCodec.releaseOutputBuffer(encoderStatus, false);
                if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                	// when EOS come.
               		mIsCapturing = false;
                    break;      // out of while
                }
            }
        }
    }

drain()方法主要是要排出mediaCodec已经编码好的数据,然后放入muxer中去也进行混合处理。
encoderStatus = mMediaCodec.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC);取出编码的状态。当这个状态值为MediaCodec.INFO_OUTPUT_FORMAT_CHANGED时,codec的输出格式已经改变了,这时候去取出输出格式并将其传入给muxer内。

final MediaFormat format = mMediaCodec.getOutputFormat();
mTrackIndex = muxer.addTrack(format);
final ByteBuffer encodedData = encoderOutputBuffers[encoderStatus];
                if (encodedData == null) {
                	// this never should come...may be a MediaCodec internal error
                    throw new RuntimeException("encoderOutputBuffer " + encoderStatus + " was null");
                }
                if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
                	// You shoud set output format to muxer here when you target Android4.3 or less
                	// but MediaCodec#getOutputFormat can not call here(because INFO_OUTPUT_FORMAT_CHANGED don't come yet)
                	// therefor we should expand and prepare output format from buffer data.
                	// This sample is for API>=18(>=Android 4.3), just ignore this flag here
					if (DEBUG) Log.d(TAG, "drain:BUFFER_FLAG_CODEC_CONFIG");
					mBufferInfo.size = 0;
                }

                if (mBufferInfo.size != 0) {
                	// encoded data is ready, clear waiting counter
            		count = 0;
                    if (!mMuxerStarted) {
                    	// muxer is not ready...this will prrograming failure.
                        throw new RuntimeException("drain:muxer hasn't started");
                    }
                    // write encoded data to muxer(need to adjust presentationTimeUs.
                   	mBufferInfo.presentationTimeUs = getPTSUs();
                   	muxer.writeSampleData(mTrackIndex, encodedData, mBufferInfo);
					prevOutputPTSUs = mBufferInfo.presentationTimeUs;
                }
                // return buffer to encoder
                mMediaCodec.releaseOutputBuffer(encoderStatus, false);
                if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                	// when EOS come.
               		mIsCapturing = false;
                    break;      // out of while
                }

这段代码是将编码好的数据以及butterInfo的内容写入到muxer里面去,并且将buffer释放给codec。视频方面的编码混合过程不再赘述了。

二、MediaMuxer介绍
在官方文档的介绍中,MediaMuxer最多仅支持一个视频track和一个音频track,所以如果有多个音频track可以先把它们混合成为一个音频track,然后再使用MediaMuxer封装到mp4容器中。通常视频编码使用H.264(AVC)编码,音频编码使用AAC编码,在MediaFormat中我们可以看到各种编码格式:

public static final String MIMETYPE_VIDEO_AVC = "video/avc";
public static final String MIMETYPE_AUDIO_AAC = "audio/mp4a-latm";
public static final String MIMETYPE_TEXT_CEA_608 = "text/cea-608";
...

构造函数使用new MediaMuxer(String path, int format):

MediaMuxer mMediaMuxer = new MediaMuxer(mOutputVideoPath, 
                MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

添加媒体通道,该函数需要传入MediaFormat对象,通常从MediaExtractor或者MediaCodec中获取,如果希望自己创建的话可以直接new或者通过该类如下静态方法创建

MediaFormat.createAudioFormat(...);
MediaFormat.createVideoFormat(...);
MediaFormat.createSubtitleFormat(...);

把MediaFormat添加到MediaMuxer后记录返回的track index,添加完所有track后调用start方法:

videoTrackIndex = mMediaMuxer.addTrack(format);
audioTrackIndex = mMediaMuxer.addTrack(format);
mMediaMuxer.start();

然后就可以调用MediaMuxer.writeSampleData()向mp4文件中写入数据了

	mBufferInfo.presentationTimeUs = getPTSUs();
    muxer.writeSampleData(mTrackIndex, encodedData, mBufferInfo);

info.size 必须填入数据的大小
info.flags 需要给出是否为同步帧/关键帧
info.presentationTimeUs 必须给出正确的时间戳,注意单位是 us
最后关闭以及释放资源:

mMediaMuxer.stop();
mMediaMuxer.release();

三、demo学习
关于使用MediaCodec和MediaMuxer生成MP4视频的demo,可以参考AudioVideoRecordingDemo学习

参考链接:
Android音视频处理之MediaMuxer
Android音视频处理之MediaCodec

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中录制屏幕并同时录取麦克风音频和内部音频需要使用 MediaProjection 和 MediaCodec。下面是一个大致的思路: 1. 获取 MediaProjection 对象。 ``` MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE); Intent permissionIntent = mediaProjectionManager.createScreenCaptureIntent(); startActivityForResult(permissionIntent, REQUEST_CODE); ``` 2. 在 onActivityResult() 方法中获取 MediaProjection 对象。 ``` @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) { mMediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data); } } ``` 3. 创建 AudioRecord 对象,用于录取麦克风音频。 ``` private void startRecordingAudio() { mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_IN_HZ, CHANNEL_CONFIG, AUDIO_FORMAT, BUFFER_SIZE_IN_BYTES); mAudioRecord.startRecording(); } ``` 4. 创建 MediaCodec 对象,用于编码屏幕和音频数据。 ``` private void prepareEncoder() { mMediaCodec = MediaCodec.createEncoderByType(MIME_TYPE); MediaFormat mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, VIDEO_WIDTH, VIDEO_HEIGHT); mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, VIDEO_BITRATE); mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, VIDEO_FRAME_PER_SECOND); mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, VIDEO_I_FRAME_INTERVAL); mMediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); mInputSurface = mMediaCodec.createInputSurface(); mMediaCodec.start(); } ``` 5. 在录制过程中,循环从麦克风和 MediaCodec 中读取音频和视频数据,并将它们合并后写入 MP4 文件。 ``` private void record() { while (mIsRecording) { int inputBufferIndex = mMediaCodec.dequeueInputBuffer(TIMEOUT_US); if (inputBufferIndex >= 0) { ByteBuffer inputBuffer = mMediaCodec.getInputBuffer(inputBufferIndex); inputBuffer.clear(); int size = mVirtualDisplay.getDisplay().getWidth() * mVirtualDisplay.getDisplay().getHeight() * 4; mVirtualDisplay.getDisplay().getRealMetrics(mDisplayMetrics); Bitmap bitmap = mImageReader.acquireLatestImage().getPlanes()[0].getBuffer().toBitmap(); bitmap = Bitmap.createScaledBitmap(bitmap, mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels, false); inputBuffer.put(bitmapToNV21(bitmap, mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels)); mMediaCodec.queueInputBuffer(inputBufferIndex, 0, size, System.nanoTime() / 1000, 0); } MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); int outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, TIMEOUT_US); if (outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { MediaFormat mediaFormat = mMediaCodec.getOutputFormat(); mMediaMuxerWrapper.addTrack(mediaFormat); mMediaMuxerWrapper.start(); } else if (outputBufferIndex >= 0) { ByteBuffer outputBuffer = mMediaCodec.getOutputBuffer(outputBufferIndex); if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) { bufferInfo.size = 0; } if (bufferInfo.size != 0) { bufferInfo.presentationTimeUs = System.nanoTime() / 1000; mMediaMuxerWrapper.writeSampleData(outputBuffer, bufferInfo); } mMediaCodec.releaseOutputBuffer(outputBufferIndex, false); } int readResult = mAudioRecord.read(mAudioBuffer, 0, mAudioBuffer.length); if (readResult > 0 && mIsRecording) { mMediaMuxerWrapper.writeAudioData(mAudioBuffer, readResult); } } } ``` 其中 `mMediaMuxerWrapper` 是一个封装了 MediaMuxer 的工具类,用于将音频和视频数据写入 MP4 文件。 需要注意的是,上面的代码仅供参考,实际应用中可能存在一些问题,例如音频和视频的同步问题等,在实际使用中需要根据具体情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值