Search code examples
androidperformancefileandroid-contentresolvermediametadataretriever

Getting individual image of mp3 file is too slow


I am trying to get the image of mp3 file on my phone. I've been struggling a few days and now I know;

  • Firstly, I use a content provider with this code

        `       Uri allSongsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
                String[] projection = {
                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.DATA,
                        MediaStore.Audio.Media.DISPLAY_NAME,
                        MediaStore.Audio.Media.DURATION,
                        MediaStore.Audio.Media.ALBUM,
                        MediaStore.Audio.Media.ALBUM_ID,
                        MediaStore.Audio.Media.ALBUM_KEY,
                        MediaStore.Audio.Media.DATE_MODIFIED
                };
                String sortOrder = MediaStore.Video.Media.DATE_MODIFIED + " DESC";
    

    And I create my cursor like this;

    Cursor cursor = ctx.getContentResolver().query(allSongsUri, projection, null, null, sortOrder);

In there I have all my mp3 files. That's ok. Now I want to get their's cover image.

  • If I use MediaMetadataRetriver's getEmbeddedPicture method like this

    mediaMetadataRetriever.setDataSource(localeMusic.getPath()); 
    localeMusic.setImage(mediaMetadataRetriever.getEmbeddedPicture());
    

    it took about 6-7 seconds with nearly 40-50 file. Because getEmbeddedPicture() is too slow!.

  • Also tried to get album_id and query another cursor to MediaStore.Audio.Albums and I saw all album id is the same because all of them is the same folder. I don't want to show their Album image. I want to show the file's cover image. I tried this like here But in there, we are getting file's albums image. That is not I ask.

Where can I find the file's image path? Where can the MetadataRetriever class get it with getEmbeddedPicture? Where is that embedded picture?

Thanks. Best regards


Solution

  • mediaMetadataRetriever.getEmbeddedPicture() is a native method and every native method call has a price because JNI calls takes time. So, if you iterate such calls, you may lost a lot of time. You may try to call this method asynchronously on demand and cache the result. Try to combine with glide This will solve two of your problem at the same time, glide calls is naturally asnyc, so you don't need to implement an AsyncTask class also it caches your images.

    This is the basic glide usage:

    Glide.with(context).load(mediaMetadataRetriever.getEmbeddedPicture());
    

    I encourage you to read glide documents. It has lots of other features.

    Hope this helps.