Android各种设备的采样频率不同,输入的声道数也不同,如果采用固定的采样频率和声道数,那么得到的AudioRecorder不一定能够正常初始化。
为了正常使用,需要尝试各种不同的参数,得到在此设备上可以用的AudioRecorder实例。代码如下:
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."); }