我希望将我的应用程序录制的MP3文件存储到Android 10的新“Scoped Storage”中的音乐文件夹中,使用MediaStore这个类。这种方法效果很好,但是文件名是以时间戳(例如1576253519449)命名的,并且没有.mp3扩展名。 如果我手动添加扩展名,文件将被正确记录。 我该如何使用
fileName + ".mp3"
来为文件命名?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();
}
}
另一个问题是:MediaStore.Audio.Media.RELATIVE_PATH
只适用于 Android 10。如何与早期版本保持兼容性?
编辑:
为了实现兼容性,您只需删除 values.put(MediaStore.Audio.Media.RELATIVE_PATH, "Music/Recordings/");
:文件将直接保存在 Music 目录中。
或者使用 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
仅在 Android 10 上添加子目录。