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.
You can't use
getContentUriForPath
with a folder, there isn't any content registered at this path. In this casegetContentUriForPath
return the standardEXTERNAL_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: