简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM