AudioRecord object not initializing in a project

2019-02-17 05:04发布

问题:

When I am trying to record an audio through my Nexus 5 using following code

record = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_8BIT, BYTE_OF_SAMPLE * bufferSampleSize);
record.startRecording();

Then I am getting following exceptions in logcat:

E/AudioRecord: AudioFlinger could not create record track, status: -1
E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -1.
E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
E/AndroidRuntime: FATAL EXCEPTION: Thread-855
E/AndroidRuntime: Process: com.*.*, PID: 14206
E/AndroidRuntime: java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.
E/AndroidRuntime:     at android.media.AudioRecord.startRecording(AudioRecord.java:885)
E/AndroidRuntime:     at com.*.*.MainActivity$Looper.run(MainActivity.java:265)
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x9e476d00

I've added following line in manifest file.

<uses-permission android:name="android.permission.RECORD_AUDIO" />

I've tested AudioRecord object not initializing. None of those solutions working.

But its working in another project. Is there anything missing?

回答1:

Got the solution: Recently I updated my phone to Marshmallow. In Marshmallow there is a new permission system. I switched on these permissions as bellow the recording works just fine.



回答2:

I used this for recording. find the complete code from here Android Audio recording example

private void startRecording() {
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
        mRecorder.setAudioEncodingBitRate(48000);
    } else {
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mRecorder.setAudioEncodingBitRate(64000);
    }
    mRecorder.setAudioSamplingRate(16000);
    mOutputFile = getOutputFile();
    mOutputFile.getParentFile().mkdirs();
    mRecorder.setOutputFile(mOutputFile.getAbsolutePath());

    try {
        mRecorder.prepare();
        mRecorder.start();
        mStartTime = SystemClock.elapsedRealtime();
        mHandler.postDelayed(mTickExecutor, 100);
        Log.d("Voice Recorder","started recording to "+mOutputFile.getAbsolutePath());
    } catch (IOException e) {
        Log.e("Voice Recorder", "prepare() failed "+e.getMessage());
    }
}