android AudioRecorder簡單心得

1.如何創建一個有效的AudioRecorder實例

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.");  
}  

 

 

2.常見錯誤

1.有些設備上面,即使你得到瞭有效的AudioRecorder實例,在audioRecord.startRecording()的時候還會報ERROR_BAD_VALUE錯誤。

這有可能是你使用瞭AudioManager而沒有釋放導致的。

其他錯誤都可以在網絡上找到答案。

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *