使用mediaStore中的mediaplayer在ActivityResult上播放一首歌

时间:2015-02-25 13:34:24

标签: android mediastore

我想从MediaStore.Audio中挑选一首歌。我得到了URi,并在烘烤后进行测试。但它不是使用媒体播放器播放。

 Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);

 startActivityForResult(intent, 1234);

在ActivityResult上

if(requestCode == 1234 && resultCode == RESULT_OK)
{
    Uri fortsting = getIntent().getData();

    Uri uriSound= data.getData();

    Toast.makeText(context, "USound " + uriSound.toString() + " tsting  "+ fortsting.toString() , Toast.LENGTH_LONG).show();

    //String extra = getRealPathFromURI(uriSound);

    try
    {
        playSong(uriSound);
    }
    catch (IllegalArgumentException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IllegalStateException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //play(extra); 
}

我还尝试使用

获取getRealPath
private String getRealPathFromURI(Uri contentUri) 
    {
        String[] proj = { MediaStore.Audio.Media.DATA };
        CursorLoader loader = new CursorLoader(context, contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);

        if(cursor.getCount()==0 || cursor==null)
            return null;

        cursor.moveToFirst();
        return cursor.getString(column_index);

    }

1 个答案:

答案 0 :(得分:1)

据我所知,问题在于,即使你正确地获得了uri,这首歌也不会在媒体播放器中打开?

看看这些主题,可能很有用:Android How to get a single song's ID info from a know URISelect a music file to play with MediaPlayer

还请发布playSong()方法的内容。它应该是这样的:

private void play(Context context, Uri uri) {
        try {
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(context, uri);         
            mp.start();
          } catch (IllegalArgumentException e) {
          // TODO Auto-generated catch block
             e.printStackTrace();
          } catch (SecurityException e) {
          // TODO Auto-generated catch block
             e.printStackTrace();
          } catch (IllegalStateException e) {
          // TODO Auto-generated catch block
             e.printStackTrace();
          } catch (IOException e) {
          // TODO Auto-generated catch block
             e.printStackTrace();
          }
    }