Search code examples
androidillegalstateexceptionandroid-mediarecorder

Illegal State Exception on Media Recorder


I want to use Media Recorder to record and save an audio file to the sd card. The debugger has shown that the line recorder.start() raises an IllegalStateException. The code is taken from the android dev website and the only change is to the file name and path.

When I reach the error in the debugging menu, I am shown the View class which says:

Source not found. The source attachment does not contain the source for the file View.class. You can change the source attachment by clicking Change Attached Source below:

canRecord is a boolean set initially to true, which dictates which method is called in an onClick function. That functionality is working.

@SuppressLint("SimpleDateFormat")
private void record(){

    SimpleDateFormat timeStampFormat = new SimpleDateFormat("MM/dd/yyyy");
    String audio_path = Environment.getExternalStorageDirectory() + "/resources/resources/WI1/";
    String fileName = username +"-"+ timeStampFormat.format(new Date())+".mp4"; 
    audio_button.setText("Recording");

    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setOutputFile(audio_path+fileName);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    try {
        recorder.prepare();
    } catch (IOException e) {
        Toast.makeText(this, "Can't record audio at this time", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
    canRecord = false;
    recorder.start();
} // record

This is the stop recording function, although it has never reached this point.

private void stopRecording(){
    audio_button.setText("Attach Audio");
    recorder.stop();
    recorder.release();
}

Finally, I have added the following permissions to the manifest:

<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How can I solve this? Thanks!


Solution

  • May be there is problem in filename you are giving to the recorder.Try this:

    String audio_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/resources/resources/WI1/";
        String fileName = audiopath+"-"+ timeStampFormat.format(new Date())+".mp4";
    

    May it helps..