Android - 将URI转换为棒棒糖上的文件路径

时间:2015-01-10 17:48:37

标签: android uri android-mediaplayer android-5.0-lollipop

我目前正在尝试为音频制作媒体播放器。我现在正在运行棒棒糖。我遇到了为媒体播放器设置dataSource的问题。首先,这是我设置dataSource的方式:

public void playSong() {
    player.reset();
    Song selSong = songs.get(songPos);
    long currSong = selSong.getId();
    //Get Uri of song
    Uri trackUri = ContentUris.withAppendedId(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currSong);
    try {
        //Tell the player the song to play
        player.setDataSource(getApplicationContext(), trackUri);
    } catch (Exception e) {
        Log.e("MUSIC SERVICE", "Error setting data source", e);
        Log.d("URI Path", trackUri.toString());
    }

    //Will prepare the song and call onPrepare of player
    player.prepareAsync();
}

Uri出来了:

  

内容://媒体/外部/音频/媒体/ 22

我做了一些研究,根据我的理解,在Android 4.1之后,你不能再使用URI作为dataSource了。当我使用上面的代码运行此应用程序时,我会收到此错误:

E/MediaPlayer﹕ Unable to create media player
E/MUSIC SERVICE﹕ Error setting data source
    java.io.IOException: setDataSource failed.: status=0x80000000
            at android.media.MediaPlayer.nativeSetDataSource(Native Method)

所以现在我需要将URI转换为文件路径并将其作为dataSource提供。而且,经过更多的研究,似乎kitkat改变了URI的提供方式,因此难以从URI获取文件路径。但是,我不确定这个更改是否会持续存在于Android Lollipop 5.0.2中。

基本上,我有一首歌的URI,但我需要为dataSource提供除URI之外的其他内容。有没有什么方法可以在Lollipop上转换URI,如果没有,我怎么才能提供dataSource只知道歌曲的id?感谢。

1 个答案:

答案 0 :(得分:0)

Lollipop决定从系统中获取另一个课程。 (有人说它来自KitKat,但我还没有在KitKat上遇到它)。下面的代码是在lollipop上获取文件路径

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(uri))
    {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];

        Uri contentUri = null;
        if ("audio".equals(type)) 
        {
            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }

        final String selection = "_id=?";
        final String[] selectionArgs = new String[] {
                split[1]
        };

        String filePath = getDataColumn(context, contentUri, selection, selectionArgs);
    }

isMediaDocument:

public static boolean isMediaDocument(Uri uri)
{
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

getDataColumn:

private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs)
{
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst())
        {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

如果您仍有问题,this是检查图像,音频,视频,文件等的完整答案。