如何获取播放音频文件的音频路径?

How to get audio path to play audio file?

这是我获取歌曲列表的代码:

  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;
    }

我想通过将其路径提供给 music player() 方法来播放该歌曲。

您可以获得这样的完整路径:

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

因此,您的函数将是:

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;
}

试试这个

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