您可以讓媒體播放器應用程式透過查詢外部媒體的 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 解決方案。請參閱更多資訊。
以下頁面將說明錄製、儲存及播放音訊和影片的相關主題: