Toast.makeText(MainActivity.this, "Recording...", Toast.LENGTH_SHORT).show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 6s
Toast.makeText(MainActivity.this, "Stopped Recording", Toast.LENGTH_SHORT).show();
mediaRecorder.stop();
mediaRecorder.release();
setupMediaRecorder();
}
}, 6000);
The app crashes after 6 seconds when I start recording, here is my setup media recorder function:
private void setupMediaRecorder()
{
mediaRecorder= new MediaRecorder();
mediaRecorder.setAudioSamplingRate(8000);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.OGG);
// mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.OGG);
mediaRecorder.setOutputFile(pathSave);
}
logcat: The error occurs at mediaRecorder.Stop(); in handler
2019-10-10 01:11:49.942 21574-21574/com.example.parkinsonsdisease E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.parkinsonsdisease, PID: 21574
java.lang.IllegalStateException
at android.media.MediaRecorder._stop(Native Method)
at android.media.MediaRecorder.stop(MediaRecorder.java:1378)
at com.example.parkinsonsdisease.MainActivity$1$1.run(MainActivity.java:93)
See the documentation:
public void stop ()
...
Throws
IllegalStateException if it is called before start()
As @LeoLeontev mentioned, it's most likely because you haven't called prepare()
and start()
.
Any call to stop()
must be preceded by a call to start()
, and start()
must be preceded by a call to prepare()
.
In other words,
private void setupMediaRecorder()
{
mediaRecorder= new MediaRecorder();
...
mediaRecorder.prepare();
}
private void startRecording()
{
mediaRecorder.start();
}
See this diagram for reference: MediaRecorder State Diagram
Also, please see the MediaRecorder
documentation here .
After following the steps given in MediaRecorder State diagram , I used set encoder and output format in this order and solved the problem facing above:
private void setupMediaRecorder()
{
mediaRecorder= new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setAudioSamplingRate(8000);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(pathSave);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.