Android获取音乐专辑封面图

1、思路介绍

step1:获取音频文件专辑ID

音频文件的详细信息,通过多媒体数据库获取,里面有包括标题、演唱家、专辑名、歌曲长度等在内的各种信息

step2:根据专辑ID继续获取专辑封面图

根据专辑ID找到对应的专辑文件,并转换成Bitmap

2、代码演示

ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        cursor.moveToFirst();
        do {
            Music m = new Music();
            m.name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            m.artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            m.album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
            m.path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            m.length = Integer.parseInt(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION)));
            //获取专辑ID
            int albumId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
            //根据专辑ID获取到专辑封面图
            m.thumbBitmap = getAlbumArt(albumId);

            musicList.add(m);
        } while (cursor.moveToNext());
        cursor.close();
/**
     * 根据专辑ID获取专辑封面图
     * @param album_id 专辑ID
     * @return
     */
    private Bitmap getAlbumArt(int album_id) {
        String mUriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[]{"album_art"};
        Cursor cur = context.getContentResolver().query(Uri.parse(mUriAlbums + "/" + Integer.toString(album_id)), projection, null, null, null);
        String album_art = null;
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        cur.close();
        Bitmap bm = null;
        if (album_art != null) {
            bm = BitmapFactory.decodeFile(album_art);
        } else {
            bm = BitmapFactory.decodeResource(getResources(), R.drawable.default_cover);
        }
        return bm;
    }

你可能感兴趣的:(学习笔记,Android)