I’m using AudioRecorder to record short audio clips but I’m getting IllegalStateException when calling AudioRecord.start() I’ve been looking for hours but can’t find the cause of this…
I’ve set Audio Rec + Write External Storage permissions.
Here’s a piece of my code:
// main activity...
// Audio inits
final MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getTempPath());
…
// called the sound rec async
new SoundComponent(tvmic, pb, tb).execute(recorder);
// SoundComponent.java
// Getting IllegalStateException when calling recorder[0].start();
[..]
protected Long doInBackground(MediaRecorder... recorder) {
try {
recorder[0].prepare();
} catch (IOException e) {
Log.e("100", "prepare() failed");
}
while (tb.isChecked())
{
//publishProgress();
//recorder[0].prepare();
recorder[0].start(); // here it were it throws
try {
Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// int amplitude = recorder[0].getMaxAmplitude();
recorder[0].stop();
}
// TODO Auto-generated method stub
return null;
}
[..]
public String getTempPath() // audio temp path
{
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
path+="/temp/audiorectemp.3gp";
return path;
}
Starting and stopping the
MediaRecordermultiple times in a loop probably isn’t a good idea. Look closely at what you’re doing, I’ve trimmed your code to make it easier to see…It probably isn’t throwing an exception the first time you call
start()but it will on the second loop. See the state machine diagram…MediaRecorderAlso, to detect when the
doInBackground(...)thread should be exited, ther is a method onAsyncTaskwhich can be called from the UI thread to cancel it.The loop should ideally be
while (!isCancelled())and you should call theAsyncTask.cancel(...)method from theonCheckedChangedlistener oftbin the mainActivitycode (assumingtbis aCheckBoxor some otherCompoundButton).