Я знаю, что этот вопрос задавали много, но никто не решил мою проблему. MediaRecorder отлично работает при записи звука, но при нажатии кнопки, чтобы остановить его, он выдает java.lang.IllegalStateException
. Заранее спасибо. Вот код:
File rootPath = new File(Environment.getExternalStorageDirectory(), "Recording");
if(!rootPath.exists()) {
rootPath.mkdirs();
}
buttonStart = (ImageButton) findViewById(R.id.RecordingButton);
buttonStop = (Button) findViewById(R.id.StopRecordingButton);
buttonStart.setEnabled(true);
buttonStop.setEnabled(false);
buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(checkPermission()) {
datetimeLog = DateString();
AudioSavePathInDevice = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recording/" + datetimeLog + "_AudioRecording.3gp";
try {
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
Toast.makeText(MainActivity.this, "Recording Started...", Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println(mediaRecorder);
mediaRecorder.stop();
//mediaRecorder.reset();
mediaRecorder.release();
mediaRecorder = null;
buttonStart.setEnabled(true);
buttonStop.setEnabled(false);
Toast.makeText(MainActivity.this, "Recording Stopped", Toast.LENGTH_LONG).show();
showAddItemDialog(MainActivity.this);
}
});
}
private String DateString() {
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy-h-m-s");
String formattedDate = df.format(c);
return formattedDate;
}
private void showAddItemDialog(final Context c) {
final EditText taskEditText = new EditText(c);
AlertDialog dialog = new AlertDialog.Builder(c)
.setTitle("Save Recording as?")
.setMessage("Name of Audio Recording (Make this a short)")
.setView(taskEditText)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
logName = taskEditText.getText().toString().replaceAll("\n","");
//AudioSavePathInDevice
//datetimeLog
//save to file
String toWrite = logName + "," + AudioSavePathInDevice + "," + datetimeLog + "\n";
myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recording/Logs.txt");
try {
buff = new BufferedWriter ( new FileWriter ( myFile,true));
buff.append(toWrite);
buff.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
File file = new File(AudioSavePathInDevice);
boolean deletedfile = file.delete();
}
}).create();
dialog.show();
}
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO, WAKE_LOCK}, RequestPermissionCode);
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(MainActivity.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), WAKE_LOCK);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED && result2 == PackageManager.PERMISSION_GRANTED;
}
}
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
Вот сообщение об ошибке:
E/MediaRecorder: stop called in an invalid state: 4
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ee.project, PID: 29167
java.lang.IllegalStateException
at android.media.MediaRecorder.stop(Native Method)
at com.example.project.MainActivity$2.onClick(MainActivity.java:114)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)