Android MediaCodec 使用例子

时间:2022-08-27 18:54:32
 
 

Android MediaCodec 使用例子

下面的例子使用MediaCodec 录制到文件的例子


1
public class AvcEncoder { 2 3 private MediaCodec mediaCodec; 4 private BufferedOutputStream outputStream; 5 6 public AvcEncoder() { 7 File f = new File(Environment.getExternalStorageDirectory(), "Download/video_encoded.264"); 8 touch (f); 9 try { 10 outputStream = new BufferedOutputStream(new FileOutputStream(f)); 11 Log.i("AvcEncoder", "outputStream initialized"); 12 } catch (Exception e){ 13 e.printStackTrace(); 14 } 15 16 mediaCodec = MediaCodec.createEncoderByType("video/avc"); 17 MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", 320, 240); 18 mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 125000); 19 mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 15); 20 mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar); 21 mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5); 22 mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); 23 mediaCodec.start(); 24 } 25 26 public void close() { 27 try { 28 mediaCodec.stop(); 29 mediaCodec.release(); 30 outputStream.flush(); 31 outputStream.close(); 32 } catch (Exception e){ 33 e.printStackTrace(); 34 } 35 } 36 37 // called from Camera.setPreviewCallbackWithBuffer(...) in other class 38 public void offerEncoder(byte[] input) { 39 try { 40 ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers(); 41 ByteBuffer[] outputBuffers = mediaCodec.getOutputBuffers(); 42 int inputBufferIndex = mediaCodec.dequeueInputBuffer(-1); 43 if (inputBufferIndex >= 0) { 44 ByteBuffer inputBuffer = inputBuffers[inputBufferIndex]; 45 inputBuffer.clear(); 46 inputBuffer.put(input); 47 mediaCodec.queueInputBuffer(inputBufferIndex, 0, input.length, 0, 0); 48 } 49 50 MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); 51 int outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo,0); 52 while (outputBufferIndex >= 0) { 53 ByteBuffer outputBuffer = outputBuffers[outputBufferIndex]; 54 byte[] outData = new byte[bufferInfo.size]; 55 outputBuffer.get(outData); 56 outputStream.write(outData, 0, outData.length); 57 Log.i("AvcEncoder", outData.length + " bytes written"); 58 59 mediaCodec.releaseOutputBuffer(outputBufferIndex, false); 60 outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0); 61 62 } 63 } catch (Throwable t) { 64 t.printStackTrace(); 65 } 66 67 }

这个例子配置了编码格式、视频大小、比特率、帧率等参数,然后在camera 预览的回调函数里把yuv420数据推送给mediacodec,编码后取出nalu,写入到文件。