mediacodec解码h264
时间: 2023-10-05 19:10:26 浏览: 112
MediaCodec是Android平台提供的一个编码和解码的API,可以用来对音视频数据进行编解码,其中包括H.264视频编解码。下面是一个简单的示例代码,可以用来解码H.264视频数据:
```
MediaCodec codec = MediaCodec.createDecoderByType("video/avc");
MediaFormat format = MediaFormat.createVideoFormat("video/avc", width, height);
format.setByteBuffer("csd-0", ByteBuffer.wrap(sps));
format.setByteBuffer("csd-1", ByteBuffer.wrap(pps));
codec.configure(format, surface, null, 0);
codec.start();
ByteBuffer[] inputBuffers = codec.getInputBuffers();
ByteBuffer[] outputBuffers = codec.getOutputBuffers();
while (!isEOS) {
int inIndex = codec.dequeueInputBuffer(10000);
if (inIndex >= 0) {
ByteBuffer buffer = inputBuffers[inIndex];
buffer.clear();
int sampleSize = extractor.readSampleData(buffer, 0);
if (sampleSize < 0) {
codec.queueInputBuffer(inIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
isEOS = true;
} else {
codec.queueInputBuffer(inIndex, 0, sampleSize, extractor.getSampleTime(), 0);
extractor.advance();
}
}
int outIndex = codec.dequeueOutputBuffer(info, 10000);
switch (outIndex) {
case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED:
outputBuffers = codec.getOutputBuffers();
break;
case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED:
format = codec.getOutputFormat();
break;
case MediaCodec.INFO_TRY_AGAIN_LATER:
break;
default:
ByteBuffer buffer = outputBuffers[outIndex];
codec.releaseOutputBuffer(outIndex, true);
break;
}
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
isEOS = true;
}
}
```
其中,`sps`和`pps`是H.264视频的序列参数集和图像参数集,`extractor`是用来读取视频数据的`MediaExtractor`对象,`surface`是用来显示解码后的视频的`Surface`对象。这段代码通过不断从`extractor`中读取视频数据,将其放入解码器中进行解码,并将解码后的数据输出到`Surface`中显示。
阅读全文