解碼過程分為兩個過程:
1.擷取h264視屏流,並進視屏流放入到解碼器中的buffer中
2.擷取解碼器的buffer ,並擷取buffer中解碼後的資料,並將其設定到SurfaceView 上進行顯示
顯示介面:
mSurfaceView = (SurfaceView) findViewById(R.id.sv);mSurfaceHolder = mSurfaceView.getHolder();mSurfaceHolder.addCallback(this);
在surfaceCreated回調中開啟2.中讀取解碼資料的迴圈線程
public class HardDecodeThread extends Thread{@Overridepublic void run() {try {mMediaCodec = MediaCodec.createDecoderByType("video/avc");MediaFormat format = MediaFormat.createVideoFormat("video/avc", 1280, 720);mMediaCodec.configure(format, mSurfaceHolder.getSurface(), null, 0);mMediaCodec.start();//注意開啟編碼,不然後面的會報錯showLog("start get output veido info");while(isPlay){BufferInfo bufInfo = new BufferInfo();int outputIndex = 0;while((outputIndex = mMediaCodec.dequeueOutputBuffer(bufInfo,20 * 1000)) >= 0 ){mMediaCodec.releaseOutputBuffer(outputIndex, true);}if(outputIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED){showLog("INFO_OUTPUT_BUFFERS_CHANGED");}else if(outputIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED){showLog("INFO_OUTPUT_FORMAT_CHANGED");}}if(mMediaCodec != null){mMediaCodec.stop();mMediaCodec.release();mMediaCodec = null;}} catch (Exception e) {e.printStackTrace();showLog("不支援寫入程式碼_error:" + e.getMessage());}}}
進行1部分:不斷擷取h264碼流進行解碼
if(mMediaCodec != null){ByteBuffer[] buffers = mMediaCodec.getInputBuffers();int inputBufferIndex = mMediaCodec.dequeueInputBuffer(20 * 1000);showLog("inputBufferIndex:" + inputBufferIndex);if(inputBufferIndex >= 0){ByteBuffer buffer = buffers[inputBufferIndex];buffer.clear();buffer.put(data);mMediaCodec.queueInputBuffer(inputBufferIndex, 0, data.length, 0, 0);//data表示h264的位元組數組}}