我试图使用AudioRecord
,但无法正确初始化录制。我有两个设备,其中一个运行良好,但另一个不断给出例外。
我的代码:
bufferSize = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT);
AudioRecord recorder = new AudioRecord(AudioSource.DEFAULT, rate,channelConfig, audioFormat, bufferSize);
为什么这是错误的,正确的做法是什么?
最佳答案
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;
}
设备很可能不支持16位编码->AudioFormat.encoding_pcm_16bit:-)