android 扫描本地音乐文件
时间: 2023-08-02 17:16:09 浏览: 152
你可以使用Android自带的MediaStore类来扫描本地音乐文件。下面是一个简单的示例代码:
```
private void scanMusicFiles() {
// 定义要查询的列
String[] projection = new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.SIZE
};
// 定义查询条件,只查询音频文件
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
// 查询音乐文件
Cursor cursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
null
);
// 遍历查询结果
if (cursor != null) {
while (cursor.moveToNext()) {
// 获取音乐文件的信息
long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));
// 打印音乐文件的信息
Log.d(TAG, "id: " + id);
Log.d(TAG, "path: " + path);
Log.d(TAG, "title: " + title);
Log.d(TAG, "artist: " + artist);
Log.d(TAG, "album: " + album);
Log.d(TAG, "duration: " + duration);
Log.d(TAG, "size: " + size);
}
cursor.close();
}
}
```
注意:需要在AndroidManifest.xml文件中添加读取外部存储的权限:
```
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
阅读全文