I have a method that attempts to create an AudioRecord
. Different phones support different sample rates, channel configs and audio formats. So the method tries to create an AudioRecord
for each of them and return the first that works.
private AudioRecord getAudioRecord() {
for (int rate: sampleRates) {
for (int audioFormat: audioFormats) {
for (int channelConfig: channelConfigs) {
String description = rate + "Hz, bits: " + audioFormat
+ ", channel: " + channelConfig;
Log.d(TAG, "Trying: " + description);
int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize == AudioRecord.ERROR
|| bufferSize == AudioRecord.ERROR_BAD_VALUE) {
Log.d(TAG, "Failed: This rate/channel config/format is not supported");
continue;
}
AudioRecord recorder = new AudioRecord(AudioSource.MIC, rate, channelConfig, audioFormat, bufferSize);
if (recorder.getState() == AudioRecord.STATE_UNINITIALIZED) {
Log.d(TAG, "Failed: Recorder is uninitialized");
continue;
}
Log.d(TAG, "Success: " + description);
return recorder;
}
}
}
Log.e(TAG, "Failed all rates. Does the device have a microphone?");
return null;
}
The problem is return recorder
never happens!
Here is my logcat output:
On the highlighted line (8000 / 3 / 12) there is no error, but also no success.
If I use no continue
as said in the comments below, it still doesn't return!
private AudioRecord getAudioRecord() {
for (int rate: sampleRates) {
for (int audioFormat: audioFormats) {
for (int channelConfig: channelConfigs) {
String description = rate + "Hz, bits: " + audioFormat
+ ", channel: " + channelConfig;
Log.d(TAG, "Trying (2): " + description);
int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize != AudioRecord.ERROR && bufferSize != AudioRecord.ERROR_BAD_VALUE) {
AudioRecord recorder = new AudioRecord(AudioSource.MIC, rate, channelConfig, audioFormat, bufferSize);
if (recorder.getState() == AudioRecord.STATE_INITIALIZED) {
Log.d(TAG, "Success: " + description);
return recorder;
} else {
Log.d(TAG, "Failed: Recorder is uninitialized");
}
} else {
Log.d(TAG, "Failed: This rate/channel config/format is not supported");
}
}
}
}
Log.e(TAG, "Failed all rates. Does the device have a microphone?");
return null;
}
There's no problem with the return statement, you simply never reach it because your AudioRecord never initializes (Most examples out there don't check it, even though they probably should)
As a brief sanity check you may want to check your Manifest file to verify you have the proper permissions to record audio in the first place, given that access to the microphone is a hardware feature that may/may not exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With