【问题标题】:How to cache audio for offline use in Android Studio如何在 Android Studio 中缓存音频以供离线使用
【发布时间】:2019-04-02 02:39:07
【问题描述】:

我正在开发一个 Android 应用程序,我需要在用户播放它时从我的网站获取指定的音频文件,但我不想每次都流式传输或下载它,只是第一次。所以我正在考虑缓存它并在用户需要时离线播放。所以请提出任何方法来做到这一点。或者如果存在任何其他方法而不是缓存like downloading the actual file to file storage and play whenever needed

【问题讨论】:

  • 您可以使用RetrofitRoom 构建数据库缓存。

标签: android


【解决方案1】:

如果你需要缓存文件,你应该使用 createTempFile()。例如,以下方法从 URL 中提取文件名,并在应用的内部缓存目录中创建一个具有该名称的文件:

private File getTempFile(Context context, String url) {
    File file;
    try {
        String fileName = Uri.parse(url).getLastPathSegment();
        file = File.createTempFile(fileName, null, 
context.getCacheDir());
    } catch (IOException e) {
        // Error while creating file
    }
    return file;
}

您还可以在此处查看有关缓存文件的更多信息。

https://developer.android.com/training/data-storage/files.html#WriteCacheFileInternal

希望这会有所帮助。

【讨论】:

  • 或者只是将其写入内部存储 - 这一切都取决于您是否想要由操作系统控制的缓存行为。我倾向于使用存储,以便更可预测。
猜你喜欢
  • 1970-01-01
  • 2016-06-07
  • 2014-02-22
  • 1970-01-01
  • 2018-08-22
  • 2012-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多