Android Mediaplayer 空点异常 (Java)

Android Mediaplayer Null point Exception (Java)

我正在尝试使用给定的 uri 创建 Mediaplayer 会话。但它会导致 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());
    }

给定 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

你能告诉我我做错了什么吗?谢谢

试试这个:

            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();

这段代码有两种写法,都在设备上测试过

首先,确保你正确处理android.permission.READ_EXTERNAL_STORAGE并且你确实有正确的Uri。
MediaPlayer.create(this, uri); 如果上下文或 uri 无效,将失败。

MediaPlayer.create(this, uri); 本身已经为播放器做好了准备,因此在这种情况下您 不需要 .prepareAsync()。你的代码很好用。

另一种方式:


    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());
    }