I am trying to use AudioRecord
, but I am unable to initialize recording quite right. I have two devices, on one of them it works well, but the other keeps giving exceptions.
My code:
bufferSize = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT);
AudioRecord recorder = new AudioRecord(AudioSource.DEFAULT, rate,channelConfig, audioFormat, bufferSize);
Why is this wrong and what is the proper way of doing it ?
private int[] mSampleRates = new int[] { 8000, 11025, 22050, 44100 };
int bufferSize;
AudioRecord audioInput = findAudioRecord();
public AudioRecord findAudioRecord() {
for (int rate : mSampleRates) {
for (short audioFormat : new short[] {
AudioFormat.ENCODING_PCM_8BIT,
AudioFormat.ENCODING_PCM_16BIT }) {
for (short channelConfig : new short[] {
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.CHANNEL_IN_STEREO }) {
try {
Log.d("Mic2", "Attempting rate " + rate
+ "Hz, bits: " + audioFormat
+ ", channel: " + channelConfig);
bufferSize = AudioRecord.getMinBufferSize(rate,
channelConfig, audioFormat);
if (RECORDINGDURATION * sampleRate != AudioRecord.ERROR_BAD_VALUE) {
// check if we can instantiate and have a
// success
AudioRecord recorder = new AudioRecord(
AudioSource.DEFAULT, rate,
channelConfig, audioFormat, bufferSize);
if (recorder.getState() == AudioRecord.STATE_INITIALIZED)
sampleRate = rate;
return recorder;
}
} catch (Exception e) {
Log.e(TAG, rate + "Exception, keep trying.", e);
}
}
}
}
return null;
}
The device most likely doesn't support 16-bit encoding -> AudioFormat.ENCODING_PCM_16BIT :-)