android studio 获取内部存储的音乐的实现方法
时间: 2023-12-02 22:04:43 浏览: 71
要获取内部存储的音乐文件,可以使用以下步骤:
1. 在 AndroidManifest.xml 文件中添加读取内部存储权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
2. 使用 MediaStore 类访问内部存储中的音乐:
```java
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION
};
Cursor cursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
sortOrder
);
if (cursor != null) {
while (cursor.moveToNext()) {
// 获取歌曲信息
String id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
String displayName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
// 处理歌曲信息
Log.d(TAG, "id=" + id + ", artist=" + artist + ", title=" + title + ", data=" + data + ", display name=" + displayName + ", duration=" + duration);
}
cursor.close();
}
```
以上代码会查询内部存储中的所有音乐文件,并打印出它们的信息。你可以根据需要修改查询条件和返回的字段。
阅读全文