Search code examples
androidmediastoremediametadataretriever

Is there any way to fetch song's genre using MediaStore?


Using this method of audio file retrieval from Android's external storage

Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);

can I actually find a resonable way to fetch a genre of the given song? MediaStore class seems to provide everything else - from song's title to its composer info - except for the genre field. Should I use MediaMetadataRetriever then? If so, how drastically can creating a MediaMetadataRetriever instance for every song on a device reduce app's performance?

Maybe there are some better ways to retrieve all audio files from both external and internal storages in android?


Solution

  • As mentioned at Developer's Site,

    You can fetch the Genres of the Audio file using MediaStore.Audio.Genres

    Sample Code :

    private static String[] genresProj = {
                MediaStore.Audio.Genres.NAME,
                MediaStore.Audio.Genres._ID
        };
    
     int idIndex = cursor
                    .getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
    
     while (cursor.moveToNext()){
                    int id = Integer.parseInt(mediaCursor.getString(idIndex));
    
                    Uri uri = MediaStore.Audio.Genres.getContentUriForAudioId("external", id );
                    genresCursor = context.getContentResolver().query(uri,
                            genresProj , null, null, null);
                    int genreIndex = genresCursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);                
    
    
                        while (genresCursor.moveToNext()) {
                            Log.d(TAG, "Genre = " +genresCursor.getString(genreIndex));
                        }
    
                }
            }
    

    To fetch other details of the Audio file, please check here .