10

I am trying to record audio but the start() method of MediaRecorder class throws an IllegalStateException. I use the following code:

MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile("/sdcard/");
try {
    recorder.prepare();
} catch (IllegalStateException e) {

// TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Log.i("Try","Exception");
recorder.start(); 

And following permission

<uses-permission android:name="android.permission.RECORD_AUDIO" />
user unknown
  • 35,537
  • 11
  • 75
  • 121
ram
  • 271
  • 3
  • 4
  • 9

2 Answers2

13

recorder.setOutputFile("/sdcard/"); is setting a directory, not a file.

Replace that with:

mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/youraudiofile.3gp";

Using "/sdcard" hard codes a path which is fragile, so use the above.

Also, for this to work you must add

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

to your AndroidManifest.xml

Ryan M
  • 18,333
  • 31
  • 67
  • 74
DJC
  • 3,243
  • 3
  • 27
  • 31
7

IllegalstateException is thrown when the MediaRecorder.prepare method is not called, or called after MediaRecorder.start, or called before configuring audio/video sources, format and encoders.

The correct order of configuration mentioned in camera developer guide in the Android documentation:

  1. camera unlock
  2. control of camera to media recorder -> setCamera
  3. set audio/video source, format,encoder
  4. prepare
  5. start
Ryan M
  • 18,333
  • 31
  • 67
  • 74
user1302884
  • 783
  • 1
  • 8
  • 16
  • 1
    This is the only thing that worked for me. Changing the order of format and encoder made it work. The order is source, format, encoder. Thanks!! – Prashanth Mar 30 '17 at 19:10