I have strange problem with my MediaRecorder. It records voice, make a file with recording. But when I want to stop recording using stop() method, it throws IllegalStateException. Generally I have used setMaxDuration() method, so usually I have ending recording using OnInfoListener and it works properly. But I want also to stop MediaRecorder in the OnTouchListener of the ImageView. My code is here:
private static String OUTPUT_FILE;
private void prepareRecording() throws Exception {
OUTPUT_FILE = "/sdcard/temp.3gpp";
File outFile = new File(OUTPUT_FILE);
if (outFile.exists())
outFile.delete();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(OUTPUT_FILE);
recorder.setMaxDuration(10000);
try {
recorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
}
private void startRecording() {
ImageView image = (ImageView) this.findViewById(R.id.image);
image.post(new Runnable() {
@Override
public void run() {
try {
prepareRecording();
} catch (Exception e) {
e.printStackTrace();
}
image.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (recorder != null)
recorder.stop();
return true;
}
});
recorder.setOnInfoListener(new OnInfoListener() {
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
if (recorder != null && what == 800){
recorder.stop();
}
}
});
}});
}
When I have touched the ImageView I have FATAL EXCEPTION java.lang.IllegalStateException at the line with code recorder.stop(). I have tested my code and I have realized that MediaRecorder seems to be not started. Therefore I have IllegalStateException at recorder.stop(). But when recording stops, I can find on my sdcard recording file. Whats wrong with my code?
I have also AnimationDrawable connected to the my image. It works properly.
I have resolved my problem. It is necessary to start new thread in onTouch method to avoid eceptions.