Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PCM to AAC or MP4 file without MediaMuxer

I need to convert a PCM file to AAC or MP4 file. Until now, I did it with MediaCodec and MediaMuxer, But MediaMuxer is supported from Android 4.3. Is there a method to do the conversion without the use of MediaMuxer?

My code is this:

MediaMuxer mux = null;
try {
    File inputFile = new File(filePath + ".pcm");
    FileInputStream fis = new FileInputStream(inputFile);
    mux = new MediaMuxer(filePath + ".mp4", MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

    MediaFormat outputFormat = MediaFormat.createAudioFormat(COMPRESSED_AUDIO_FILE_MIME_TYPE,
            SAMPLING_RATE, 1);
    outputFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
    outputFormat.setInteger(MediaFormat.KEY_BIT_RATE, COMPRESSED_AUDIO_FILE_BIT_RATE);

    MediaCodec codec = MediaCodec.createEncoderByType(COMPRESSED_AUDIO_FILE_MIME_TYPE);
    codec.configure(outputFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
    codec.start();

    ByteBuffer[] codecInputBuffers = codec.getInputBuffers();
    ByteBuffer[] codecOutputBuffers = codec.getOutputBuffers();

    MediaCodec.BufferInfo outBuffInfo = new MediaCodec.BufferInfo();

    byte[] tempBuffer = new byte[BUFFER_SIZE];
    boolean hasMoreData = true;
    double presentationTimeUs = 0;
    int audioTrackIdx = 0;
    int totalBytesRead = 0;
    int percentComplete;

    do {

        int inputBufIndex = 0;
        while (inputBufIndex != -1 && hasMoreData) {
            inputBufIndex = codec.dequeueInputBuffer(CODEC_TIMEOUT_IN_MS);

            if (inputBufIndex >= 0) {
                ByteBuffer dstBuf = codecInputBuffers[inputBufIndex];
                dstBuf.clear();

                int bytesRead = fis.read(tempBuffer, 0, dstBuf.limit());
                if (bytesRead == -1) { // -1 implies EOS
                    hasMoreData = false;
                    codec.queueInputBuffer(inputBufIndex, 0, 0, (long) presentationTimeUs, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
                } else {
                    totalBytesRead += bytesRead;
                    dstBuf.put(tempBuffer, 0, bytesRead);
                    codec.queueInputBuffer(inputBufIndex, 0, bytesRead, (long) presentationTimeUs, 0);
                    presentationTimeUs = 1000000l * (totalBytesRead / 2) / SAMPLING_RATE;
                }
            }
        }

        // Drain audio
        int outputBufIndex = 0;
        while (outputBufIndex != MediaCodec.INFO_TRY_AGAIN_LATER) {

            outputBufIndex = codec.dequeueOutputBuffer(outBuffInfo, CODEC_TIMEOUT_IN_MS);
            if (outputBufIndex >= 0) {
                ByteBuffer encodedData = codecOutputBuffers[outputBufIndex];
                encodedData.position(outBuffInfo.offset);
                encodedData.limit(outBuffInfo.offset + outBuffInfo.size);

                if ((outBuffInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0 && outBuffInfo.size != 0) {
                    codec.releaseOutputBuffer(outputBufIndex, false);
                } else {

                    mux.writeSampleData(audioTrackIdx, codecOutputBuffers[outputBufIndex], outBuffInfo);
                    codec.releaseOutputBuffer(outputBufIndex, false);
                }
            } else if (outputBufIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
                outputFormat = codec.getOutputFormat();
                Log.v("AUDIO", "Output format changed - " + outputFormat);
                audioTrackIdx = mux.addTrack(outputFormat);
                mux.start();
            } else if (outputBufIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
                Log.e("AUDIO", "Output buffers changed during encode!");
            } else if (outputBufIndex != MediaCodec.INFO_TRY_AGAIN_LATER){
                Log.e("AUDIO", "Unknown return code from dequeueOutputBuffer - " + outputBufIndex);
            }
        }
        percentComplete = (int) Math.round(((float) totalBytesRead / (float) inputFile.length()) * 100.0);
        Log.v("AUDIO", "Conversion % - " + percentComplete);
    } while (outBuffInfo.flags != MediaCodec.BUFFER_FLAG_END_OF_STREAM);

    fis.close();
    mux.stop();
    mux.release();
like image 528
Luca Romagnoli Avatar asked Oct 12 '15 15:10

Luca Romagnoli


1 Answers

As you already pointed out, there's no public system API compatible with older version of Android for this kind of job.

Anyway, you can pursue a custom solution using a native encoder (like FFMPEG). I can suggested you the following: timsu/android-aac-enc

Android AAC Encoder project

Extraction of Android Stagefright VO AAC encoder with a nice Java API.

This project offers an easy Java API for the underlying JNI encoder, and it should be ready to use since the native library is already compiled for generic ARM architectures (please note that I haven't tested it). The whole library is just 500kb so it won't fatten your APK that much.

For a quick test, import in your project the following parts:

  1. Java bindings for the native AAC encorder
  2. Pre-compiled AAC encoder .so library
  3. Example of usage (speech encoding)

You should be able to easily adapt the example to your code.

like image 73
bonnyz Avatar answered Nov 16 '22 07:11

bonnyz