Search code examples
androidandroid-music-player

Android: How to get audio detail from audio file


I have my music app started from external applications using intent data as music file.

So I have the mp3 audio URI something like this

file:///storage/emulated/0/Music/Tamil/I%20(2014)/Ennodu%20Nee%20Irundhaal.mp3

how to get the audio details from URI ie, the Media.TITLE , Media.ALBUM , Media._ID


Solution

  • You can converto file URI to canonical path and get infomation of music file with ContentsProvider like below codes.

    String path = new File(new URI(path).getPath()).getCanonicalPath();
    Cursor c = context.getContentResolver().query(
        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
        new String[] {
                MediaStore.Audio.Media.ALBUM,
                MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media.TRACK,
                MediaStore.Audio.Media.TITLE,
                MediaStore.Audio.Media.DISPLAY_NAME,
                MediaStore.Audio.Media.DATA,
                MediaStore.Audio.Media.DURATION,
                MediaStore.Audio.Media.YEAR
        },
        MediaStore.Audio.Media.DATA + " = ?",
        new String[] {
                path
        },
        "");
    
    if (null == c) {
        // ERROR
    }
    
    while (c.moveToNext()) {
        c.getString(c.getColumnIndex(MediaStore.Audio.Media.ALBUM));
        c.getString(c.getColumnIndex(MediaStore.Audio.Media.ARTIST));
        c.getString(c.getColumnIndex(MediaStore.Audio.Media.TRACK));
        c.getString(c.getColumnIndex(MediaStore.Audio.Media.TITLE));
        c.getString(c.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
        c.getString(c.getColumnIndex(MediaStore.Audio.Media.DATA));
        c.getString(c.getColumnIndex(MediaStore.Audio.Media.DURATION));
        c.getString(c.getColumnIndex(MediaStore.Audio.Media.YEAR));
    }