简体   繁体   English

将图像编码为视频(Mediacodec)

[英]Encode Images to Video (Mediacodec)

I need to encode a series of 10 bitmaps into a video using Mediacodec. 我需要使用Mediacodec将一系列10位图编码为视频。 I do not want to use FFmpeg or Jcodec because its very slow. 我不想使用FFmpeg或Jcodec,因为它非常慢。

I have searched on the Internet but can't seem to find a fully working sample code that i can modify. 我在Internet上进行了搜索,但似乎找不到可以修改的完全正常的示例代码。

Here is what I've tried: 这是我尝试过的:

mMediaCodec = MediaCodec.createEncoderByType("video/avc");
mMediaFormat = MediaFormat.createVideoFormat("video/avc", 320, 240);
mMediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 125000);
mMediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 15);
mMediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,       MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar);
mMediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);
mMediaCodec.configure(mMediaFormat, null, null,    MediaCodec.CONFIGURE_FLAG_ENCODE);
mMediaCodec.start();
mInputBuffers = mMediaCodec.getInputBuffers();

 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
 image.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); //    image is the bitmap
  byte[] input = byteArrayOutputStream.toByteArray();

  int inputBufferIndex = mMediaCodec.dequeueInputBuffer(-1);
   if (inputBufferIndex >= 0) {
   ByteBuffer inputBuffer = mInputBuffers[inputBufferIndex];
   inputBuffer.clear();
   inputBuffer.put(input);
   mMediaCodec.queueInputBuffer(inputBufferIndex, 0, input.length, 0, 0);
   }

Your code example creates an encoder that expects YUV420 image buffers, but you're feeding it PNG compressed data (which btw is just a glorified ZIP file format, not a image representation format). 您的代码示例创建了一个期望YUV420图像缓冲区的编码器,但您正在向其提供PNG压缩数据(顺便说一句,它只是一种美化的ZIP文件格式,而不是图像表示格式)。

You should convert each bitmap'z pixels from ARGB to YUV, and feed that buffer to the encoder. 您应该将每个位图的z像素从ARGB转换为YUV,并将该缓冲区输入编码器。 Obviously they should match with the frame width and height in the encoder's setup. 显然,它们应与编码器设置中的框架宽度和高度匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM