user6007737
user6007737

Reputation: 49

How to get audio path to play audio file?

This is my code that gets list of songs:

  List<String> getsonglist() {

        List<String> songlist = new ArrayList<>();
        ContentResolver contentResolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        Cursor cursor = contentResolver.query(uri, null, null, null, null);
        if (cursor == null) {
            // query failed, handle error.
        } else if (!cursor.moveToFirst()) {
            // no media on the device
        } else {
            int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
            int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
            do {
                long thisId = cursor.getLong(idColumn);
                String thisTitle = cursor.getString(titleColumn);
                // ...process entry...

                songlist.add(thisTitle);
            } while (cursor.moveToNext());
        }


        return songlist;
    }

I want to play that song by giving its path to music player() method.

Upvotes: 2

Views: 5139

Answers (2)

Shanaka Nuwan
Shanaka Nuwan

Reputation: 175

Try this one

String fullPath = cursor.getString(cursor.getColumnIndex("_data"));

Upvotes: 1

EmJiHash
EmJiHash

Reputation: 623

You can get full path like this:

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

So, Your function would be:

List<String> getsonglist() {

    List<String> songlist = new ArrayList<>();
    ContentResolver contentResolver = getContentResolver();
    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

    Cursor cursor = contentResolver.query(uri, null, null, null, null);
    if (cursor == null) {
        // query failed, handle error.
    } else if (!cursor.moveToFirst()) {
        // no media on the device
    } else {
        do {

            String fullPath = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            // ...process entry...
            Log.e("Full Path : ", fullPath);


            songlist.add(fullPath);
        } while (cursor.moveToNext());
    }


    return songlist;
}

Upvotes: 4

Related Questions