在Android中,簡(jiǎn)單的說(shuō)可以使用MediaMuxer來(lái)封裝編碼后的視頻流和音頻流到mp4容器中,MediaMuxer從api18開始提供,可以封裝編碼后的視頻流和音頻流到視頻文件中。目前MediaMuxer支持的文件輸出格式包括MP4,webm和3gp:
函數(shù)
構(gòu)造函數(shù)
構(gòu)造函數(shù) | 說(shuō)明 |
---|---|
MediaMuxer(String path, int format) | path:用于存放合成的文件的路徑,不能為null;format:輸出的文件的格式,OutputFormat中的常量標(biāo)識(shí)。 |
MediaMuxer(FileDescriptor fd, int format) | Constructor. |
方法
返回值 | 方法名 | 說(shuō)明 |
---|---|---|
int | addTrack(MediaFormat format) | 添加的格式 |
void | release() | 主動(dòng)釋放資源 |
void | setLocation(float latitude, float longitude) | Set and store the geodata (latitude and longitude) in the output file. |
void | setOrientationHint(int degrees) | Sets the orientation hint for output video playback. |
void | start() | Starts the muxer. |
void | stop() | S暫停 |
void | writeSampleData(int trackIndex, ByteBuffer byteBuf, MediaCodec.BufferInfo bufferInfo) | Writes an encoded sample into the muxer. |
使用過(guò)程介紹:
-
生成MediaMuxer對(duì)象
通過(guò)new MediaMuxer(String path, int format)指定視頻文件輸出路徑和文件格式:MediaMuxer mMediaMuxer = new MediaMuxer(mOutputVideoPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
-
addTrack
addTrack(MediaFormat format),添加媒體通道,傳入MediaFormat對(duì)象,通常從MediaExtractor或者M(jìn)ediaCodec中獲取,也可以自己創(chuàng)建,后面會(huì)有文章說(shuō)明。
addTrack會(huì)返回trackindex,這個(gè)index后面會(huì)用到。//開始編碼 就會(huì)調(diào)用一次 MediaFormat outputFormat = mMediaCodec.getOutputFormat(); //配置封裝器 // 增加一路指定格式的媒體流 視頻 index = mMediaMuxer.addTrack(outputFormat);
-
調(diào)用start函數(shù)
MediaMuxer.start();
-
寫入數(shù)據(jù)
調(diào)用MediaMuxer.writeSampleData()向mp4文件中寫入數(shù)據(jù)了。每次只能添加一幀視頻數(shù)據(jù)或者單個(gè)Sample的音頻數(shù)據(jù),需要BufferInfo對(duì)象作為參數(shù)。
BufferInfo.size 必須填入數(shù)據(jù)的大小
BufferInfo.flags 需要給出是否為同步幀/關(guān)鍵幀
BufferInfo.presentationTimeUs 必須給出正確的時(shí)間戳,注意單位是 us,第二次getSampleTime()和首次getSampleTime()的時(shí)間差。//輸出緩沖區(qū) MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); //MediaCodec下節(jié)課介紹 int status = mMediaCodec.dequeueOutputBuffer(bufferInfo, 10_000); //index是addTrack(outputFormat)返回的 mMediaMuxer.writeSampleData(index, outputBuffer, bufferInfo);
-
釋放關(guān)閉資源
結(jié)束寫入后關(guān)閉以及釋放資源:MediaMuxer.stop(); MediaMuxer.release();
總結(jié):
MediaMuxer基本使用我們學(xué)完了,主要是結(jié)合MediaCodec一起來(lái)使用,后面我們會(huì)在來(lái)學(xué)習(xí)MediaCodec來(lái)一起使用,來(lái)完成編碼錄制功能。