1

I want to play a song after picking it from MediaStore.Audio. I get the URi and also test after toasting it. but it is not playing using mediaplayer.

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

 startActivityForResult(intent, 1234);

And on 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); 
}

And i also try to getRealPath using

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

    }
Xar-e-ahmer Khan
  • 1,314
  • 15
  • 23

1 Answers1

1

As I understand, the problem is that, even if you get the uri correcly, the song is not opened in the media player?

Take a look at these threads, might be useful: Android How to get a single song's ID info from a know URI and Select a music file to play with MediaPlayer

Please also post the content of playSong() method. It should be something like this:

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();
          }
    }
Community
  • 1
  • 1
A B
  • 338
  • 3
  • 10