简体   繁体   中英

Encode Images to Video (Mediacodec)

I need to encode a series of 10 bitmaps into a video using Mediacodec. I do not want to use FFmpeg or Jcodec because its very slow.

I have searched on the Internet but can't seem to find a fully working sample code that i can modify.

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).

You should convert each bitmap'z pixels from ARGB to YUV, and feed that buffer to the encoder. Obviously they should match with the frame width and height in the encoder's setup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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