Android 本地音乐扫描 - 基于 SD 卡实现
Android 本地音乐扫描 - 基于 SD 卡实现
本教程将引导您了解如何在 Android 应用中使用 SD 卡路径来扫描本地音乐文件,并获取歌曲信息,包括标题、艺术家、专辑、时长和路径等。
1. 获取 SD 卡路径
首先,您需要获取 SD 卡的路径。可以使用以下代码获取:
String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
2. 扫描音乐文件
使用 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();
}
3. 处理音乐信息
扫描到的音乐信息可以用来更新 UI 或保存到数据库中,您可以根据自己的需求进行处理。需要注意的是,由于是基于 SD 卡进行扫描,可能会存在 SD 卡被拔出的情况,需要进行异常处理。
建议:
- 在进行音乐扫描之前,检查 SD 卡是否可用。
- 在获取音乐信息后,进行必要的格式转换或处理,以确保数据完整性。
- 考虑使用异步任务或线程来执行音乐扫描,避免阻塞 UI 线程。
- 为用户提供清晰的提示,例如扫描进度或结果。
- 在处理音乐信息时,注意内存管理,防止出现内存溢出等问题。
通过本教程,您将掌握如何在 Android 应用中使用 SD 卡扫描本地音乐文件,并获取歌曲信息。您可以根据实际需要进行扩展和定制,开发出更加丰富的音乐播放功能。
原文地址: https://www.cveoy.top/t/topic/nIxi 著作权归作者所有。请勿转载和采集!