I'm trying to save my recordings to the Room database and this is almost fine, but I don't know how to create my own file path to save more than just one file. I've tried so far just add date and my own name of the file at end of file, but it didn't work. If I save standard path and then press play it works, but I can save just one file (same path). If I trying to create own path I have info in logs: Log.e(TAG, "prepare() failed");
Setup:
private void setupMediaRecorder() {
filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "myRecording.3gpp";
File file = new File(filePath);
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(file);
}
Save:
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name = String.valueOf(nameEditText.getText());
Recording recording = new Recording(name, filePath, length, currentDate);
mainViewModel.insertRecording(recording);
getDialog().dismiss();
}
});
Play:
private void play() {
playing = true;
playbackButton.setImageResource(R.drawable.ic_pause_black_true_24dp);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(getContext(), "Playing...", Toast.LENGTH_SHORT).show();
Log.d(TAG, filePath);
} catch (Exception e) {
Log.e(TAG, "prepare() failed");
}
}
SOLUTION:
I found solution of my problem. Problem was in two signs: ":" for the time and "/" for the date. These signs are using to create path of the file and media player had problem with find proper path.
Get the current date and time, then use that as the file name.
private void setupMediaRecorder() {
filePath = Environment.getExternalStorageDirectory().toString() + File.separator + getDateAndTime()+".3gpp";
File file = new File(filePath);
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(file);
}
private String getDateAndTime(){
@SuppressLint("SimpleDateFormat") DateFormat dfDate = new SimpleDateFormat("yyyyMMdd");
String date=dfDate.format(Calendar.getInstance().getTime());
@SuppressLint("SimpleDateFormat") DateFormat dfTime = new SimpleDateFormat("HHmm");
String time = dfTime.format(Calendar.getInstance().getTime());
return date + "-" + time;
}
By doing this, you will always use a different name for your file.