[英]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
.发生警报时,我想在
MediaPlayer
播放音频。 The MediaPlayer is created and run successfully with default ringtone but remains null
in case of an audio file chosen from external storage. MediaPlayer 使用默认铃声创建并成功运行,但在从外部存储中选择音频文件的情况下保持为
null
。
I have provided following permission in manifest:我在清单中提供了以下许可:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
The code for mediaPlayer
setting inside BroadcastReciever
class: BroadcastReciever
类中mediaPlayer
设置的代码:
@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:以下是我选择音频文件并使用意图将其Uri 数据发送到
BroadcastReciever
类的活动代码:
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.在
AlarmReciever
类中也成功接收了Uri
。 However the MediaPlayer
instance is not created with it.但是
MediaPlayer
实例不是用它创建的。
The file that you want to play maybe is not supported by android. android 可能不支持您要播放的文件。 Try with a different file and check the answer in this question: Android MediaPlayer.Create() returns null
尝试使用不同的文件并检查此问题中的答案: Android MediaPlayer.Create() 返回 null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.