Illegal State Exception when calling MediaCodec.co

2019-01-22 16:09发布

问题:

I get the IllegalStateException on MediaCodec.configure() line, I'm trying to record audio using MediaCodec. This only occur on some phones, on tabs everything is fine. This particular crash example is from Samsung Galaxy S4. Exception traces:

01-22 17:33:38.379: V/ACodec(16541): [OMX.google.aac.decoder] Now Loaded
01-22 17:33:38.379: V/ACodec(16541): onConfigureComponent
01-22 17:33:38.379: W/ACodec(16541): [OMX.google.aac.decoder] Failed to set standard component role 'audio_encoder.aac'.
01-22 17:33:38.379: E/ACodec(16541): [OMX.google.aac.decoder] configureCodec returning error -2147483648
01-22 17:33:38.379: E/MediaCodec(16541): Codec reported an error. (omx error 0x80001001, internalError -2147483648)
01-22 17:33:38.384: D/AndroidRuntime(16541): Shutting down VM
01-22 17:33:38.384: W/dalvikvm(16541): threadid=1: thread exiting with uncaught exception (group=0x418d0700)
01-22 17:33:38.414: W/BugSenseHandler(16541): Transmitting crash Exception Unable to resolve host "bugsense.appspot.com": No address associated with hostname
01-22 17:33:41.404: E/AndroidRuntime(16541): FATAL EXCEPTION: main
01-22 17:33:41.404: E/AndroidRuntime(16541): java.lang.IllegalStateException
01-22 17:33:41.404: E/AndroidRuntime(16541):    at android.media.MediaCodec.native_configure(Native Method)
01-22 17:33:41.404: E/AndroidRuntime(16541):    at android.media.MediaCodec.configure(MediaCodec.java:259)
01-22 17:33:41.404: E/AndroidRuntime(16541):    at com.example.poc.MyRenderer.startRecordPressed(MyRenderer.java:344)

Audio format declaration:

    MediaFormat format = new MediaFormat();
    format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm");
    format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
    format.setInteger(MediaFormat.KEY_SAMPLE_RATE, 44100);
    format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
    format.setInteger(MediaFormat.KEY_BIT_RATE, 64000);

Audio encoder initialization:

        mAudioEncoder = MediaCodec.createEncoderByType("audio/mp4a-latm");
        mAudioEncoder.configure(mAudioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); //<-This line fails
        mAudioEncoder.start();

Does anyone have any idea what that might be? What's strange is that it only happens on some devices. Any suggestions would be welcome!

回答1:

I see this same error when trying to configure a video codec on certain Samsung devices running Jellybean (4.1.2). In many cases, setting KEY_MAX_INPUT_SIZE to 0 (before calling configure) in the format parameters will fix it:

mVideoFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 0);

I found this solution when researching a similar bug (https://stackoverflow.com/questions/15105843/mediacodec-jelly-bean#=), and have been surprised at how many codec configuration bugs this fixes. That said, I haven't tried it on Audio codecs so no guarantee it will work in your case :/