Search code examples
javaandroidbroadcastreceiveruriandroid-mediaplayer

MediaPlayer is null on a Uri from external storage


I have created an Alarm app. Upon Alarm fire I want to play an audio in MediaPlayer. The MediaPlayer is created and run successfully with default ringtone but remains null in case of an audio file chosen from external storage.

I have provided following permission in manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

The code for mediaPlayer setting inside BroadcastReciever class:

 @Override
    public void onReceive(Context context, Intent intent) {

        try {
            alarm_tone = Uri.parse(intent.getStringExtra("alarm_tone"));
             }catch (Exception ex){
                              alarm_tone = Settings.System.DEFAULT_RINGTONE_URI;
                              }
        Log.d("Uri", "Alarm tone recieved: " + (alarm_tone));     //result: OK

        MediaPlayer mediaPlayer=MediaPlayer.create(context, alarm_tone);

        mediaPlayer.setScreenOnWhilePlaying(true); //gives null pointer exception on this line in case of external Uri,, i.e. mediaPlayer is null in this case
        mediaPlayer.setLooping(true);
        mediaPlayer.start();
    }

Following is the code of my activity where I am choosing audio file and sending its Uri data using intent to BroadcastReciever class:

btnRingTone.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);

                  startActivityForResult(intent, 10);
              }
          });


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

        if(resultCode == RESULT_OK && requestCode == 10){
            ringTone=data.getData();
        }
    }
    public void setAlarm(){
    Intent i=new Intent(this, AlarmReciver.class);
    i.putExtra("alarm_tone", ringtone.toString());
    ...
    }

The audio file is selected successfully. The Uri is also received in AlarmReciever class successfully. However the MediaPlayer instance is not created with it.


Solution

  • The file that you want to play maybe is not supported by android. Try with a different file and check the answer in this question: Android MediaPlayer.Create() returns null