[英]Android Mediaplayer Null point Exception (Java)
I am trying to create Mediaplayer session with given uri.我正在尝试使用给定的 uri 创建 Mediaplayer session。 but it causes NullpointerException .
但它会导致NullpointerException 。
Uri uri = Uri.parse(path);
// Creating MediaPlayer with given song's URI
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
mediaPlayer = MediaPlayer.create(this, uri);
try {
// Setting the MediaPlayer Listener
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
mediaPlayer.start();
changeSeekbar();
}
});
} catch (Exception e) {
Log.e("ERROR", e.toString());
}
Given Logcat:给定Logcat:
2020-04-07 22:21:05.289 12237-12237/com.example.musicappresearch2 E/Path: /storage/emulated/0/Music/Alone - Viren.mp3
2020-04-07 22:21:05.289 12237-12237/com.example.musicappresearch2 E/ERROR: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setOnPreparedListener(android.media.MediaPlayer$OnPreparedListener)' on a null object reference
Could you Tell me What i am doing wrong?你能告诉我我做错了什么吗? Thanks.
谢谢。
There are two ways to write this code, both tested on the device这段代码有两种写法,都在设备上测试过
First of all, make sure you handle android.permission.READ_EXTERNAL_STORAGE
correctly and you really have correct Uri.首先,确保您正确处理
android.permission.READ_EXTERNAL_STORAGE
并且您确实拥有正确的 Uri。
MediaPlayer.create(this, uri);
will fail if either context or uri are invalid.如果上下文或 uri 无效,则将失败。
MediaPlayer.create(this, uri);
which itself already prepares player so you don't need .prepareAsync()
in this situation.它本身已经准备好播放器,因此在这种情况下您不需要
.prepareAsync()
。 and your code is good to go.并且您的代码对 go 很好。
another way:另一种方式:
mediaPlayer = new MediaPlayer(); // hence, we don't use .create, manually instantiate
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(this, uri);
mediaPlayer.setOnPreparedListener(mp -> {
mediaPlayer.start();
});
/* use async, if you don't want to block UI thread
keep in mind, this should be called after setting listener
because it might prepare even until the listener has been set */
mediaPlayer.prepareAsync();
} catch (Exception e) {
Log.e("ERROR", e.toString());
}
Try this:尝试这个:
Uri uri = Uri.parse(path);
mediaPlayer = new MediaPlayer();
try {
// mediaPlayer.setDataSource(String.valueOf(uri));
mediaPlayer.setDataSource(MainActivity.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.