今天跟大家分享一下如何获取本地音乐文件中的各种音乐信息,包括音乐的歌名,歌手,曲长,专辑,专辑图片
private String tilte;//歌名 private String artist;//歌手 private Bitmap bitmap;//专辑海报 private long duration;//时长 private String path_music;//当前播放的歌曲路径ContentResolver musicResolver = getContentResolver(); Cursor cursor = null;cursor = musicResolver.query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Audio.Media.DATA + "= ? ", new String[]{path_music}, null); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); long ID = cursor.getLong(cursor .getColumnIndex(MediaStore.Audio.Media._ID)); //音乐id tilte = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)); artist = cursor.getString(cursor .getColumnIndex(MediaStore.Audio.Media.ARTIST)); // 艺术家 String album = cursor.getString(cursor .getColumnIndex(MediaStore.Audio.Media.ALBUM)); //专辑 duration = cursor.getLong(cursor .getColumnIndex(MediaStore.Audio.Media.DURATION)); // 时长 long size = cursor.getLong(cursor .getColumnIndex(MediaStore.Audio.Media.SIZE)); String url = cursor.getString(cursor .getColumnIndex(MediaStore.Audio.Media.DATA)); long albumId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)); bitmap = getMusicBitemp(getApplicationContext(), ID, albumId);
下面还有getMusicBitmap方法
private static final Uri sArtworkUri = Uri .parse("content://media/external/audio/albumart"); public static Bitmap getMusicBitemp(Context context, long songid, long albumid) { Bitmap bm = null; // 专辑id和歌曲id小于0说明没有专辑、歌曲,并抛出异常 if (albumid < 0 && songid < 0) { throw new IllegalArgumentException( "Must specify an album or a song id"); } try { if (albumid < 0) { Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart"); ParcelFileDescriptor pfd = context.getContentResolver() .openFileDescriptor(uri, "r"); if (pfd != null) { FileDescriptor fd = pfd.getFileDescriptor(); bm = BitmapFactory.decodeFileDescriptor(fd); } } else { Uri uri = ContentUris.withAppendedId(sArtworkUri, albumid); ParcelFileDescriptor pfd = context.getContentResolver() .openFileDescriptor(uri, "r"); if (pfd != null) { FileDescriptor fd = pfd.getFileDescriptor(); bm = BitmapFactory.decodeFileDescriptor(fd); } else { return null; } } } catch (FileNotFoundException ex) { } //如果获取的bitmap为空,则返回一个默认的bitmap if (bm == null) { Resources resources = context.getResources(); Drawable drawable = resources.getDrawable(R.drawable.back_iv); //Drawable 转 Bitmap BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; bm = bitmapDrawable.getBitmap(); } return Bitmap.createScaledBitmap(bm, 150, 150, true); }
除去上面使用到的 还有
String year = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.YEAR));//获取发行年份
Int size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));//获取歌曲文件大小
等等。