Home » Android » MediaPlayer doesn't work?

MediaPlayer doesn't work?

Posted by: admin November 1, 2017 Leave a comment

Questions:

I want to play audio files with MediaPlayer. Audio files are not in resource.
What I want to do is like this.

  1. get the file path.
  2. register the file path to realm db.
  3. fetch the file path from realm db.
  4. set the file path to MediaPlayer (IOException happens here)
  5. play

IOException happens When I call MediaPlayer#setDataSource(path).
I dont know where i am doing wrong

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_choose) {
        Intent intent = new Intent();
        intent.setType("audio/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 999);
        return true;
    }
     return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 999 && resultCode == RESULT_OK) {
    final Uri uri = data.getData();
    _realmObj.executeTransactionAsync(new Realm.Transaction() {
        @Override
            public void execute(Realm bgRealm) {
                MyDb db = bgRealm.where(Song.class).equalTo("id", songIndex).findFirst();
                db.setSongPath(uri.getDataString());
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                buttonPlay.setVisibility(View.VISIBLE);
            }
        });
    }
    super.onActivityResult(requestCode, resultCode, data);
}

private void PlaySong(int songIndex) {
     MyDb db = _realmObj.where(Song.class).equalTo("id", songIndex).findFirst();
     Uri path = db.getSongPath();
     if (path == null) {
         return;
     }
     try {
         _mediaPlayer.setDataSource(URLDecoder.decode(path, "utf-8"));
         _mediaPlayer.prepare();
         _mediaPlayer.start();
     } catch (IllegalArgumentException e) {
         e.printStackTrace();
     } catch (IllegalStateException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     }
}
Answers: