Why does the start() method of MediaRecorder throw an IllegalStateException?

戏子无情 提交于 2021-02-07 12:00:28

问题


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" />

回答1:


Vijay, 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 AndroidManifext.xml




回答2:


It may be helpful for some one in future. IllegalstateException is thrown when the MediaRecorder. Prepare method is not called or called after Mediarecorder.start or before configuring audio/video sources,format and encoders. The correct order of configuration mentioned in camera developer guide on android documentation

  1. camera unlock
  2. control of camera to media recorder -> setCamera
  3. set audio/video source, format,encoder
  4. prepare
  5. start


来源:https://stackoverflow.com/questions/5177039/why-does-the-start-method-of-mediarecorder-throw-an-illegalstateexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!