如何使用MediaStore.Audio.Albums.ALBUM_ART显示专辑封面?

12
我想制作一个MP3播放器,希望ImageView可以显示相应歌曲的专辑封面。我尝试了以下方法,但不起作用。
albumcover = (ImageView) findViewById(R.id.cover);

String coverPath = songsList.get(songIndex).get(MediaStore.Audio.Albums.ALBUM_ART);
Drawable img = Drawable.createFromPath(coverPath);
albumcover.setImageDrawable(img);

当我尝试播放歌曲时,ImageView里只显示一个空白屏幕。


请参见以下与编程有关的内容:https://dev59.com/IXI-5IYBdhLWcg3wPFx2#28624058和https://dev59.com/1FjUa4cB1Zd3GeqPV_Gy#28624084。 - Zar E Ahmer
7个回答

27

以下是我获取歌曲专辑封面的方法:

Cursor cursor = getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, 
                new String[] {MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART}, 
                MediaStore.Audio.Albums._ID+ "=?", 
                new String[] {String.valueOf(albumId)}, 
                null);

if (cursor.moveToFirst()) {
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
    // do whatever you need to do
}

albumId 指的是该歌曲的 MediaStore.Audio.Media.ALBUM_ID

如果您正在寻找特定歌曲的专辑封面(而不是在专辑列表中),据我所知,这是一个两阶段的过程,因为 ALBUM_ARTMediaStore.Audio.Albums 的属性,不能直接作为歌曲元数据使用。


1
@AnkitSrivastava 这个字符串是专辑封面图像的路径,因此您可以将其转换为位图,例如使用BitmapFactory.decodeFile(String path) - Ken Wolf
1
@PrashantPatel,我所说的两个阶段是指据我所知,你无法直接从歌曲中获取专辑封面,因为它是专辑的属性。因此,首先您需要获取包含该歌曲的专辑,然后再从专辑中获取封面。 - Ken Wolf
1
@KenWolf 是的,你说得对。我通过Metadataretriver做到了这一点,但我想知道是否还有其他方法。谢谢你的回复。 - Prashant Patel
1
@KenWolf 现在已经很晚了,但是还有一种方法 这里。但它是如何工作的呢? - Neelay Srivastava
2
这种方法可能会在Android 10上出现问题,因为路径不可访问(EACCESS错误)。授予权限(对于External_Storage的读写权限)是不够的。 - AndrewBloom
显示剩余4条评论

11

如果您有专辑ID,则可以获取专辑图片URI:

final public static Uri sArtworkUri = Uri
            .parse("content://media/external/audio/albumart");      

Uri uri = ContentUris.withAppendedId(PlayerConstants.sArtworkUri,
                listOfAlbums.get(position).getAlbumID());

如果您有一个图像 URI,您可以使用任何图像加载器GlidePicassoUIL 来显示图片。

                               **OR**

你可以编写自己的图像加载器

public Bitmap getAlbumart(Context context, Long album_id) {
    Bitmap albumArtBitMap = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    try {

        final Uri sArtworkUri = Uri
                .parse("content://media/external/audio/albumart");

        Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);

        ParcelFileDescriptor pfd = context.getContentResolver()
                .openFileDescriptor(uri, "r");

        if (pfd != null) {
            FileDescriptor fd = pfd.getFileDescriptor();
            albumArtBitMap = BitmapFactory.decodeFileDescriptor(fd, null,
                    options);
            pfd = null;
            fd = null;
        }
    } catch (Error ee) {
    } catch (Exception e) {
    }

    if (null != albumArtBitMap) {
        return albumArtBitMap;
    }
    return getDefaultAlbumArtEfficiently(context.getResources());
}



public Bitmap getDefaultAlbumArtEfficiently(Resources resource) {

    if (defaultBitmapArt == null) {

        defaultBitmapArt = decodeSampledBitmapFromResource(resource,
                R.drawable.default_album_art, UtilFunctions
                        .getUtilFunctions().dpToPixels(85, resource),
                UtilFunctions.getUtilFunctions().dpToPixels(85, resource));

    }
    return defaultBitmapArt;
}

不要忘记调用fd.close()函数(BitmapFactory.decodeFileDescriptor函数也不会自动关闭)。 - Robin Davies

9
 ContentResolver musicResolve = getContentResolver();
    Uri smusicUri = android.provider.MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
    Cursor music =musicResolve.query(smusicUri,null         //should use where clause(_ID==albumid)
        ,null, null, null);



    music.moveToFirst();            //i put only one song in my external storage to keep things simple
    int x=music.getColumnIndex(android.provider.MediaStore.Audio.Albums.ALBUM_ART);
        String thisArt = music.getString(x);


     Bitmap bm= BitmapFactory.decodeFile(thisArt);
        ImageView image=(ImageView)findViewById(R.id.image);
        image.setImageBitmap(bm);

Ken 给出的答案也是正确的,但作为新手,我需要花费很多时间来使其正常工作。这就是为什么我上传了完整的答案。 - Kishan Kumar

3
这个方法返回一个包含歌曲路径和专辑封面的ArrayList。
public static ArrayList<CommonModel> getAllMusicPathList(Context context) {
    ArrayList<CommonModel> musicPathArrList = new ArrayList<>();
    Uri songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

    Cursor cursorAudio = context.getContentResolver().query(songUri, null, null, null, null);
    if (cursorAudio != null && cursorAudio.moveToFirst()) {

        Cursor cursorAlbum;
        if (cursorAudio != null && cursorAudio.moveToFirst()) {

            do {
                Long albumId = Long.valueOf(cursorAudio.getString(cursorAudio.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
                cursorAlbum = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
                        MediaStore.Audio.Albums._ID + "=" + albumId, null, null);

                    if(cursorAlbum != null && cursorAlbum.moveToFirst()){
                        String albumCoverPath = cursorAlbum.getString(cursorAlbum.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
                        String data = cursorAudio.getString(cursorAudio.getColumnIndex(MediaStore.Audio.Media.DATA));
                        musicPathArrList.add(new CommonModel(data,albumCoverPath ,false));
                    }

                 } while (cursorAudio.moveToNext());
        }
    }
    return musicPathArrList;
}

这是 CommonModel。

public class CommonModel {

private String path;
private boolean selected;

public String getAlbumCoverPath() {
    return albumCoverPath;
}

public void setAlbumCoverPath(String albumCoverPath) {
    this.albumCoverPath = albumCoverPath;
}

private String albumCoverPath;

public CommonModel(String path, String albumCoverPath, boolean b) {
    this.path = path;
    this.albumCoverPath=albumCoverPath;
    this.selected=b;
}

public String getPath() {
    return path;
}

public void setPath(String path) {
    this.path = path;
}

public boolean getSelected() {
    return selected;
}

public void setSelected(boolean selected) {
    selected = selected;
}
}

0

示例代码

public static Uri getAlbumArtUri(long albumId) {
    return ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), albumId);
}


ArrayList<Uri> albumArtUris = new ArrayList<>();
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{"album_id"}, null, null, null);
cursor.moveToFirst();
do {
    long ablumId = cursor.getLong(cursor.getColumnIndexOrThrow("album_id"));
    albumArtUris.add(getAlbumArtUri(ablumId));
} while (cursor.moveToNext());

0

你应该使用Uri.parse("content://media/external/audio/albumart");来查询专辑封面。第一个答案可能会在某些手机上出现异常(至少在我的手机上是这样)


0
以下代码对我有用。我知道它已经被回答过了,但对于查找参考的人可能会有用。
 public void getAlbumArt() {
    try {
        ContentResolver cr = getContentResolver();
        Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;

        Cursor cursor = cr.query(uri, null, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            int albumart = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
            do {
                String Albumids = cursor.getString(albumart);
                Albumid.add(Albumids);

            } while (cursor.moveToNext());
        }cursor.close();
    } catch (NumberFormatException e){
        e.printStackTrace();
    }
}
public void getSelectedPath(){
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String path= String.valueOf(listView.getItemAtPosition(i));

                if(path.equals("null")){
                ImageView imgv=(ImageView)view.findViewById(R.id.imageView);
                imgv.setImageResource(R.drawable.unknowalbum);
                imgv.setMaxHeight(50);
                imgv.setMaxWidth(50);

            }
            else{
                Drawable image=Drawable.createFromPath(path);
                ImageView imgview=(ImageView)view.findViewById(R.id.imageView);
                imgview.setImageDrawable(image);

            }
        }
    });
}

完整代码请访问 http://vasistaguru.blogspot.com/2017/02/get-albumart-and-trackname-using.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接