I want to store my mp3 files recorded with my app to the Music folder with MediaStore for the new "Scoped Storage" of Android 10.
This method works good, but the files are named with timestamp (e.g. 1576253519449), without .mp3
extension.
If I add the extension manually with file manager, the file is recorded correctly.
How i can use fileName + ".mp3"
to name the files?
String fileName; //Obtained by intent
MediaRecorder audioRecorder;
Uri audiouri;
ParcelFileDescriptor file;
private void startRecording() throws IOException {
ContentValues values = new ContentValues(4);
values.put(MediaStore.Audio.Media.TITLE, fileName);
values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (System.currentTimeMillis() / 1000));
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.RELATIVE_PATH, "Music/Recordings/");
audiouri = getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
file = getContentResolver().openFileDescriptor(audiouri, "w");
if (file != null) {
audioRecorder = new MediaRecorder();
audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
audioRecorder.setOutputFile(file.getFileDescriptor());
audioRecorder.setAudioChannels(1);
audioRecorder.prepare();
audioRecorder.start();
}
}
And another question: MediaStore.Audio.Media.RELATIVE_PATH
is only for Android 10.
How to maintain retrocompatibility with older releases?
EDIT:
For retrocompatibility, you can just remove values.put(MediaStore.Audio.Media.RELATIVE_PATH, "Music/Recordings/");
: the files will be saved directly in Music directory.
Or use if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
to add the subdirectory only on Android 10.
As @blackapps suggested, can be used the DISPLAY_NAME
property.