您可以通过查询 ContentResolver
来获取用户设备上的外部媒体音乐,从而让您的媒体播放器应用检索音乐。
Kotlin
val resolver: ContentResolver = contentResolver
val uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val cursor: Cursor? = resolver.query(uri, null, null, null, null)
when {
cursor == null -> {
// query failed, handle error.
}
!cursor.moveToFirst() -> {
// no media on the device
}
else -> {
val titleColumn: Int = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE)
val idColumn: Int = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID)
do {
val thisId = cursor.getLong(idColumn)
val thisTitle = cursor.getString(titleColumn)
// ...process entry...
} while (cursor.moveToNext())
}
}
cursor?.close()
Java
ContentResolver contentResolver = getContentResolver();
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = contentResolver.query(uri, null, null, null, null);
if (cursor == null) {
// query failed, handle error.
} else if (!cursor.moveToFirst()) {
// no media on the device
} else {
int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
do {
long thisId = cursor.getLong(idColumn);
String thisTitle = cursor.getString(titleColumn);
// ...process entry...
} while (cursor.moveToNext());
}
要将其与 MediaPlayer
配合使用,您可以这样做
Kotlin
val id: Long = /* retrieve it from somewhere */
val contentUri: 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
long id = /* retrieve it from somewhere */;
Uri contentUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
mediaPlayer.setDataSource(getApplicationContext(), contentUri);
// ...prepare and start...
了解详情
Jetpack Media3 是您应用中媒体播放的推荐解决方案。了解更多。
这些页面涵盖了与录制、存储和播放音频及视频相关的主题