【问题标题】:Android Q, how to save audio recording with MediaStore with the correct file name?Android Q,如何使用正确的文件名使用 MediaStore 保存录音?
【发布时间】:2019-12-13 17:09:41
【问题描述】:

我想将使用我的应用录制的 mp3 文件存储到带有 MediaStore 的 Music 文件夹中,用于 Android 10 的新“Scoped Storage”。
此方法效果很好,但文件以时间戳命名(例如 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 上添加子目录。

【问题讨论】:

  • 使用 DISPLAY_NAME。
  • 谢谢,它就像一个魅力。
  • @blackapps 我想知道如何使用媒体商店 API 对 Android Q 之前的设备执行相同操作?
  • 然后使用 .DATA 列。
  • @OMIHARISCHHANDRAMEHTA 对于 Android 10 和 11,您可以将 android:requestLegacyExternalStorage="true" 添加到清单中的 元素:stackoverflow.com/a/58379655/3605220 但开始将您的录音保存在应用程序专用文件夹中,因为在未来的 android 版本中,您将无法再创建文件夹,即使使用这种传统方法也是如此。两个whatsapp都做不到了!

标签: android file audio-recording mediastore scoped-storage


【解决方案1】:

正如@blackapps 建议的那样,可以使用DISPLAY_NAME 属性。

【讨论】:

    猜你喜欢
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多