Retrieve media from a content resolver
Stay organized with collections
Save and categorize content based on your preferences.
You can have your media player application retrieve music that the user has
on their device by querying
the ContentResolver for external media:
Kotlin
valresolver:ContentResolver=contentResolver
valuri=android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
valcursor:Cursor? =resolver.query(uri,null,null,null,null)
when{
cursor==null->{
// query failed, handle error.
}
!cursor.moveToFirst()->{
// no media on the device
}
else->{
valtitleColumn:Int=cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE)
validColumn:Int=cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID)
do{
valthisId=cursor.getLong(idColumn)
valthisTitle=cursor.getString(titleColumn)
// ...process entry...
}while(cursor.moveToNext())
}
}
cursor?.close()
Java
ContentResolvercontentResolver=getContentResolver();
Uriuri=android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursorcursor=contentResolver.query(uri,null,null,null,null);
if(cursor==null){
// query failed, handle error.
}elseif(!cursor.moveToFirst()){
// no media on the device
}else{
inttitleColumn=cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
intidColumn=cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
do{
longthisId=cursor.getLong(idColumn);
StringthisTitle=cursor.getString(titleColumn);
// ...process entry...
}while(cursor.moveToNext());
}
To use this with the MediaPlayer, you can do this:
Kotlin
valid:Long=/* retrieve it from somewhere */
valcontentUri:Uri=
ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,id)
mediaPlayer=MediaPlayer().apply{
setAudioAttributes(
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
)
setDataSource(applicationContext,contentUri)
}
// ...prepare and start...
Java
longid=/* retrieve it from somewhere */;
UricontentUri=ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,id);
mediaPlayer=newMediaPlayer();
mediaPlayer.setAudioAttributes(
newAudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
mediaPlayer.setDataSource(getApplicationContext(),contentUri);
// ...prepare and start...
Learn more
Jetpack Media3 is the recommended solution for media playback in your app. Read more about it.
These pages cover topics relating to recording, storing, and playing back audio and video: