You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RecyclerView中仅读取特定文件夹(如MyMusic)的音乐文件?

仅从特定文件夹(如MyMusic)获取歌曲的代码修改方案

要实现仅从指定文件夹(比如MyMusic)读取歌曲,只需在MediaStore的查询条件中添加文件路径筛选即可,以下是修改后的完整代码:

private void readMediaFiles() {
    ContentResolver contentResolver = context.getContentResolver();

    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    // 原音乐筛选条件 + 路径筛选条件
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0 AND " + MediaStore.Audio.Media.DATA + " LIKE ?";
    // 目标文件夹的匹配规则,%是SQL通配符,匹配任意字符
    String[] selectionArgs = new String[]{"%/MyMusic/%"};
    String sort = MediaStore.Audio.Media.ALBUM + " ASC";
    String[] projection = {MediaStore.Audio.Albums.ALBUM_ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA};
    // 传入筛选参数
    Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sort);

    if(cursor != null) {
        Msg.log(String.valueOf(cursor.getCount()));
        if(cursor.getCount() > 0) {
            while(cursor.moveToNext()) {
                @SuppressLint("Range") String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                @SuppressLint("Range") String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                @SuppressLint("Range") String albumid = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ID));
                mediaListModel = new MediaListModel(Long.parseLong(albumid), path, title);
                mediaListModelArrayList.add(mediaListModel);
            }
        }
        // 记得关闭Cursor,避免内存泄漏
        cursor.close();
    }
}

关键修改说明:

  1. 筛选条件扩展:在原有的IS_MUSIC != 0基础上,新增了MediaStore.Audio.Media.DATA LIKE ?,通过文件路径匹配目标文件夹
  2. 参数化查询:使用selectionArgs传递路径匹配规则,避免直接拼接字符串导致的SQL注入风险,同时适配不同设备的路径格式
  3. 路径匹配规则:%/MyMusic/%表示匹配所有路径中包含/MyMusic/的文件,这样不仅能读取MyMusic根目录下的歌曲,还能读取其子文件夹中的歌曲。如果只需要根目录的文件,可以调整为更精确的路径匹配

额外注意:

  • 确保你的应用已经申请了READ_EXTERNAL_STORAGE权限(Android 10及以上可能需要适配分区存储或申请MANAGE_EXTERNAL_STORAGE权限)
  • 如果MyMusic有固定的完整路径(比如/storage/emulated/0/MyMusic/),也可以将筛选条件改为MediaStore.Audio.Media.DATA LIKE ?并传入"/storage/emulated/0/MyMusic/%",匹配更精准

内容的提问来源于stack exchange,提问作者Crc Pcl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 20:20:48