Getting all audio files in a directory on android?

2020-08-01 06:52发布

I'm using the following code to get all audio files (actually their ids so I can play them later with MediaPlayer) from a directory on my android device:

ContentResolver cr = context.getContentResolver();
Uri audioUri = MediaStore.Audio.Media.getContentUriForPath(dir.getPath()); //dir is a File object representing the dir I'm looking in
Cursor audioCursor = cr.query(audioUri, null, null, null, null);

if (audioCursor != null && audioCursor.moveToFirst()) {
    int idColumn = audioCursor.getColumnIndex(MediaStore.Audio.Media._ID);

    List<Long> fileIds = new ArrayList<>();
    do {
        long id = audioCursor.getLong(idColumn);
        fileIds.add(id);
    } while (audioCursor.moveToNext());

    return fileIds;
} else { 
    return null;
}

For some reason however, it returns an array with 2904 ids for any dir I give it. I'm guessing there are 2904 audio files on my device (when I use Uri audioUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI it also returns 2904 ids). So it seems I'm using getContentUriForPath incorrectly, however the android reference doesn't give any information.

How should this work?

Some more info about what I'm trying to do (if it makes any difference in your answer): I'm still working on the code, trying out different things. Ultimately I want to play the files with MediaPlayer. I only need the audio files in that folder directly, ignoring any subfolders. They should also be ordered by filename.

标签: android
1条回答
▲ chillily
2楼-- · 2020-08-01 07:52

You can't use getContentUriForPath with a folder, there isn't any content registered at this path. In this case getContentUriForPath return the standard EXTERNAL_CONTENT_URI, for this reason you get all the ids available.

This return all the files contained in a particular folder (e.g. /storage/emulated/0/Music/), ignoring any subfolders and ordered by filename:

Cursor audioCursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                null,
                MediaStore.Audio.Media.DATA + " LIKE ? AND " + MediaStore.Audio.Media.DATA + " NOT LIKE ?",
                new String[]{path + "%", path + "%/%"},
                MediaStore.Audio.Media.DISPLAY_NAME + " ASC");

if (audioCursor != null && audioCursor.moveToFirst()) {
    int idColumn = audioCursor.getColumnIndex(MediaStore.Audio.Media._ID);

    List<Long> fileIds = new ArrayList<>();
    do {
        long id = audioCursor.getLong(idColumn);
        fileIds.add(id);
    } while (audioCursor.moveToNext());

    return fileIds;
} else { 
    return null;
}
查看更多
登录 后发表回答