android AudioRecorder simple tips to share

  • 2020-05-17 06:32:26
  • OfStack

1. How to create a valid AudioRecorder instance
The sampling frequency of various Android devices is different, and the number of sound channels input is also different. If a fixed sampling frequency and number of sound channels are adopted, the obtained AudioRecorder can be initialized normally.
In order to work properly, you need to try various parameters to get an instance of AudioRecorder available on this device. The code is as follows:

private void createAudioRecord() {   
           for (int sampleRate : new int[]{44100, 8000, 11025, 16000, 22050, 32000,   
            47250, 48000}) {   
        for (short audioFormat : new short[]{   
                AudioFormat.ENCODING_PCM_16BIT,   
                AudioFormat.ENCODING_PCM_8BIT}) {   
            for (short channelConfig : new short[]{   
                    AudioFormat.CHANNEL_IN_MONO,   
                    AudioFormat.CHANNEL_IN_STEREO}) {   

                // Try to initialize   
                try {   
                    recBufSize = AudioRecord.getMinBufferSize(sampleRate,   
                            channelConfig, audioFormat);   

                    if (recBufSize < 0) {   
                        continue;   
                    }   

                    audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,   
                            sampleRate, channelConfig, audioFormat,   
                            recBufSize * 2);   

                    if (audioRecord.getState() == AudioRecord.STATE_INITIALIZED) {   

                        return;   
                    }   

                    audioRecord.release();   
                    audioRecord = null;   
                } catch (Exception e) {   
                    // Do nothing   
                }   
            }   
        }   
    }   

    throw new IllegalStateException(   
            "getInstance() failed : no suitable audio configurations on this device.");   
}

2. Common mistakes
1. On some devices, even if you get a valid AudioRecorder instance, an ERROR_BAD_VALUE error will be reported at audioRecord.startRecording ().
It is possible that you used AudioManager and did not release it.
Other mistakes can be found on the Internet.

Related articles: