Search code examples
androidvoice-recordingandroid-audiorecord

AudioRecord can not be initialized


I am trying to work with audiorecorder, but I am getting illegal argument exceptions stating that the audiorecorder is not initialised.

My code is like the one shown here

private static final int RECORDER_SAMPLERATE = 44100;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;

recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,RECORDER_SAMPLERATE,  RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);                        
recorder.startRecording();

I have seen another answer which seems to work for some people but it isn't working for me AudioRecord object not initializing


Solution

  • Try this instead:

    private MediaRecorder mRecorder = null;
    private void startRecording() {
            String fileSaveName = generateNameForAudioFile();
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mRecorder.setOutputFile(fileSaveName);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
    
            try {
                mRecorder.prepare();
            } catch (IOException e) {
                Log.e(LOG_TAG, "prepare() failed");
            }
    
            mRecorder.start();
        }
    
    
    
    private void stopRecording() {
            startRecording.setEnabled(true);
            try {
                if (mRecorder != null) {
                    mRecorder.stop();
                    mRecorder.release();
                    mRecorder = null;
                }
            } catch (Exception e) {
            }
    
        }
    
    public String generateNameForAudioFile() {
    
            String audioName = GetrandFilename();
            mFileName = Environment.getExternalStorageDirectory().getPath() + "/"
                    + audioName + "myaudio" + ".3gp";
    
            );
            return mFileName;
        }
    
    
    
    @Override
        public void onPause() {
            super.onPause();
    
                try {
                    if (mRecorder != null) {
                        mRecorder.stop();
                        mRecorder.release();
                        mRecorder = null;
                    }
                } catch (Exception e) {
                }
                  }
    

    Let me know if this post is of any help.