SoFunction
Updated on 2025-04-12

Android AudioRecorder simple experience sharing


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 = (sampleRate,  
                            channelConfig, audioFormat);  

                    if (recBufSize < 0) {  
                        continue;  
                    }  

                    audioRecord = new AudioRecord(,  
                            sampleRate, channelConfig, audioFormat,  
                            recBufSize * 2);  

                    if (() == AudioRecord.STATE_INITIALIZED) {  

                        return;  
                    }  

                    ();  
                    audioRecord = null;  
                } catch (Exception e) {  
                    // Do nothing  
                }  
            }  
        }  
    }  

    throw new IllegalStateException(  
            "getInstance() failed : no suitable audio configurations on this device.");  
}