Get path of song from SD card in android

Zankhna picture Zankhna · Sep 1, 2012 · Viewed 13.8k times · Source

In my android application I want to fetch song from SD card but I am not able to get the path of that particular file.I am using android api level 7 which doesn't support following method.

Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_MUSIC);

I have also tried following code :

path = Environment.getExternalStorageDirectory();

but I don't know how to specify path of music file.Please suggest some solution.Thanx.

Answer

Chirag picture Chirag · Sep 1, 2012

Get path and song Name from SD Card. You can find the path of the song from MediaStore.

The Media provider contains meta data for all available media on both internal and external storage devices.

private String[] STAR = { "*" };

public void ListAllSongs() 
    { 
        Cursor cursor;
        Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

        if (isSdPresent()) {
            cursor = getContentResolver().query(allsongsuri, STAR, selection, null, null);

            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    do {
                        String songname = cursor
                                .getString(cursor
                                        .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                        int song_id = cursor.getInt(cursor
                                .getColumnIndex(MediaStore.Audio.Media._ID));

                        String fullpath = cursor.getString(cursor
                                .getColumnIndex(MediaStore.Audio.Media.DATA));

                        String albumname = cursor.getString(cursor
                                .getColumnIndex(MediaStore.Audio.Media.ALBUM));

                    } while (cursor.moveToNext());
                }
                cursor.close();
            }
        }
    }


public static boolean isSdPresent() 
{
    return android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);
}