以下是一个基本的示例代码,它使用Android的MediaStore API在SD卡上扫描本地音乐。

首先,你需要声明以下权限:

<uses-permission android:name='android.permission.READ_EXTERNAL_STORAGE' />

然后在你的Activity或Fragment中,你可以使用以下代码来扫描本地音乐:

private void scanLocalMusic() {
    // 定义要查询的列
    String[] projection = {
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.DATA
    };

    // 查询媒体库中的音乐文件
    Cursor cursor = getContentResolver().query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection,
            null,
            null,
            MediaStore.Audio.Media.DEFAULT_SORT_ORDER
    );

    // 遍历查询结果
    if (cursor != null) {
        while (cursor.moveToNext()) {
            long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
            String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
            String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
            String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
            long duration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
            String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));

            // 处理查询结果
            Log.d('LocalMusicScanner', 'id: ' + id);
            Log.d('LocalMusicScanner', 'title: ' + title);
            Log.d('LocalMusicScanner', 'artist: ' + artist);
            Log.d('LocalMusicScanner', 'album: ' + album);
            Log.d('LocalMusicScanner', 'duration: ' + duration);
            Log.d('LocalMusicScanner', 'path: ' + path);

            // 在这里可以将查询结果保存到数据库或其他数据结构中
        }
        cursor.close();
    }
}

该示例代码使用MediaStore.Audio.Media.EXTERNAL_CONTENT_URI来查询外部存储设备上的音乐文件。你可以使用其他URI来查询其他类型的媒体文件,如图片和视频。

如果你要在后台扫描本地音乐,请记得使用异步任务或线程来执行查询操作,以避免阻塞UI线程。

Android本地音乐扫描功能实现:基于SD卡的代码示例

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

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