How to convert a WAV file into a 3gp in Android using MediaCodec

102 views Asked by At

I have tried to perform the with the following conversion loop.

    while (true) {
        sampleSize = extractor.readSampleData(inputBuffer, 0)
        if (sampleSize < 0) break
        val presentationTimeUs = extractor.sampleTime
        val flags = extractor.sampleFlags

        val inputBufferId = codec.dequeueInputBuffer(codecTimeoutUs)

        if (inputBufferId >= 0) {
            val codecBuffer = codec.getInputBuffer(inputBufferId)
            codecBuffer?.put(inputBuffer)
            codec.queueInputBuffer(inputBufferId, 0, sampleSize, presentationTimeUs, flags)
        }

            extractor.advance()
       

        val outputBufferId = codec.dequeueOutputBuffer(bufferInfo, codecTimeoutUs)

        if (outputBufferId >= 0) {
            val codecBuffer = codec.getOutputBuffer(outputBufferId)
            muxer.writeSampleData(outputTrackIndex, codecBuffer!!, bufferInfo)
            codec.releaseOutputBuffer(outputBufferId, false)
        }
    }

The results are a an invalid .3gp file, can you help me?.

1

There are 1 answers

0
dev.bmax On

The code snippet doesn't show how MediaExtractor, MediaCodec and MediaMuxer are configured, so the picture is incomplete.

In general, the auxiliary inputBuffer must be cleared before writing and flipped before reading.

But it's easier to let the codec manager the buffers:

val inputBuffer = codec.getInputBuffer(inputBufferId)!!
val sampleSize = extractor.readSampleData(inputBuffer, 0)

Additionally, if the sampleSize is negative, you should consider it to be the end of the file and notify the codec:

codec.queueInputBuffer(inputBufferId, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM)