Select a music file to play with MediaPlayer

梦想的初衷 提交于 2019-12-01 00:37:27
ilango j

First start activity to pic media file from sd card. Replace the following code

Button openFile = (Button) this.findViewById(R.id.ButtonOpen);
    openFile.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
           Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 10);
        }
    }); 

Then in add the following code in onActivityResult

     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {

          if(resultCode == RESULT_OK && requestCode == 10){
                Uri uriSound=data.getData();
                play(this, uriSound); 
          }
      }

And call the below method to create media player and play selected audio file.

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

Looking at the source code of the creation of the MediaPlayer, it looks like this :

public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {

        try {
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(context, uri);
            if (holder != null) {
                mp.setDisplay(holder);
            }
            mp.prepare();
            return mp;
        } catch (IOException ex) {
            Log.d(TAG, "create failed:", ex);
            // fall through
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "create failed:", ex);
            // fall through
        } catch (SecurityException ex) {
            Log.d(TAG, "create failed:", ex);
            // fall through
        }

        return null;
    }

So in your case the error may be that the URI you pass in parameter is wrong or malformed, so the create method returns null. Check if the URI is correct when you create your mediaPlayer object.

Also I saw this line :

if (mButtonPlayStop.getText() == getString(R.string.play_str))

Don't use == to compare content of Strings. Use .equals() instead :

if (mButtonPlayStop.getText().equals(getString(R.string.play_str)))

If someone have difficulties with this question as I had, I did some fixes to the answers above, and this snippet should work:

private  final int SELECT_PICTURE = 1;

public void pickMusic() {
    Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i,SELECT_MUSIC);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_MUSIC){
            Uri selectedMusicUri = data.getData();
            if (selectedMusicUri != null){
                String pathFromUri = getRealPathFromURI(this, selectedMusicUri);
                MediaPlayer mp = new MediaPlayer();
                try {
                    mp.setDataSource(this, Uri.parse(pathFromUri));
                    mp.prepare();
                    mp.start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


private String getRealPathFromURI(Context context, Uri contentUri) {
    String[] projection = { MediaStore.Audio.Media.DATA };
    CursorLoader loader = new CursorLoader(context, contentUri, projection, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!