I am working on a Piano App in android which has a record functionality. It uses the device mic to record and then saves the recorded file to the device memory.
How do I correctly save a audio file in storage in an android App? I am unable to save the file inside the device. Currently I am getting a Toast message "Added file null" after I stop the recording. The uri object is giving me a null value in the Toast message. What am I doing wrong?
private void startRecording() throws IOException {
try {
String direPath = context.getExternalFilesDir(null).getAbsolutePath();
String filePath = direPath + "/recording";
audioFile = new File(filePath);
} catch (Exception e) {
Log.e("Error Tag", "external storage access error " + e.getMessage());
return;
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(audioFile.getAbsolutePath());
mediaRecorder.prepare();
mediaRecorder.start();
}
private void stopRecording(){
if(mediaRecorder != null)
mediaRecorder.stop();
saveToDisk();
}
public void saveToDisk() {
ContentResolver contentResolver = context.getContentResolver();
ContentValues values = new ContentValues();
{
long current = System.currentTimeMillis();
values.put(MediaStore.Audio.Media.TITLE, "audio" + audioFile.getName());
values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mpeg");
values.put(MediaStore.Audio.Media.DATA, audioFile.getAbsolutePath());
}
Uri uri = contentResolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
Toast.makeText(this, "Added File " + uri, Toast.LENGTH_LONG).show();
}