1. 获取SD卡路径

首先需要获取SD卡的路径,可以使用如下代码获取:

String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
  1. 扫描音乐文件

使用MediaStore.Audio进行扫描,代码如下:

String[] projection = {MediaStore.Audio.Media._ID,
        MediaStore.Audio.Media.DISPLAY_NAME,
        MediaStore.Audio.Media.TITLE,
        MediaStore.Audio.Media.DURATION,
        MediaStore.Audio.Media.ARTIST,
        MediaStore.Audio.Media.ALBUM,
        MediaStore.Audio.Media.DATA};

String selection = MediaStore.Audio.Media.DATA + " like ?";
String[] selectionArgs = {"%" + sdcardPath + "%"};

Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
        projection, selection, selectionArgs, null);

if (cursor != null) {
    while (cursor.moveToNext()) {
        // 获取音乐信息
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
        String displayName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
        String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
        long duration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
        String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
        String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
        String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));

        // 处理音乐信息
        // ...
    }
    cursor.close();
}
  1. 处理音乐信息

扫描到的音乐信息可以用来更新UI或保存到数据库中,可以根据自己的需求进行处理。其中需要注意的是,由于是基于SD卡进行扫描,可能会存在SD卡被拔出的情况,需要进行异常处理

android如何基于sd内存完成本地音乐扫描功能

原文地址: http://www.cveoy.top/t/topic/dw7E 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录