I see two issues here:
You are using a hardcoded value for
bufferSizeInBytes
. According to the documentation, if you use a value smaller thangetMinBufferSize
will result in an initialization failure. Why don't you use your value ofbufferSize
in the constructor? Also, use the same value ofchannelConfig
when callinggetMinBufferSize
.Similar to the answer in this question, someone may have not released the AudioRecord resources. You could make some changes to your if statement as shown in the code block below. If this is true, then your code will fail while trying to initialize a bit-rate of 44100, release the resources correctly and then successfully initialize a bit-rate of 8000. If you still want to have a bit-rate of 44100, use
new int[] {44100, 44100, 8000, 11025, 16000, 22050}
The code block below includes both changes to your code. Please try it and let me know what you get.
public static void getValidSampleRates() {
int desiredRate = 0;
for (int rate : new int[] {44100, 8000, 11025, 16000, 22050}) {
int bufferSize = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
if (bufferSize > 0) {
// buffer size is valid, Sample rate supported
AudioRecord audioRecorder = new AudioRecord(AudioSource.MIC, rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
if (audioRecorder.getState() != AudioRecord.STATE_INITIALIZED) {
desiredRate = -1;
audioRecorder.release();
} else {
desiredRate = rate;
break;
}
}
}
}