Search code examples
xamarin.androidmediastorealbumart

How to get the album art of a media file in Xamarin?


I've been searching for a couple of days on how to get the album art for a song (or a frame capture of a video) from a file path. All I could find is things related to Mediastore like this answer where it requires getting the album ID of the file.

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
}

But I can't find a guid on how it works, how can pass the file to Mediastore or how can I get the album ID of the media or anything... Currently I get the media information using MediaMetadataRetriever but I can't find a way to get the album art or a video thumbnail of a media file using it...

** Update :-

If Mediastore must be used to get the media files in the first place before using it to get their data, I can implement it instead of what I'm currently doing (Currently I iterate the device files to get the supported files) and it can be a better option as Mediastore supports getting data from external storages as well.

Any help is appreciated.


Solution

  • If using MediaMetadataRetriever , you can have a try with follow sample code :

    private void loadingCover(string mediaUri)
    {
        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
        mediaMetadataRetriever.SetDataSource(mediaUri);
        byte[] picture = mediaMetadataRetriever.GetEmbeddedPicture();
        Android.Graphics.Bitmap bitmap = BitmapFactory.DecodeByteArray(picture, 0, picture.Length);
        musicCover.SetImageBitmap(bitmap);
    }
    

    In addition , not forgatting to add permission :

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

    Invoke it as follow :

    File file = new File("/storage/sdcard/Movies/music1.mp4");
    if (file.Exists())
    {
        loadingCover(file.AbsolutePath);
    }