我的媒体播放器启动了一个新实例而不是停止

my mediaplayer starts a new instance instead of stopping

我正在制作一个媒体播放器来播放存储在 firebase 上的 mp3 混音。我可以让链接播放没问题。但是当我再次按下该项目时,我希望它相当于按下停止。但由于某种原因,它并没有停止,而是启动了一个新的媒体实例。有人可以告诉我我做错了什么吗?

我的代码

在我的创作中

mMediaplayer = null;

然后我的方法

 private void fetchAudioUrlFromFirebase() throws IOException {
    String mp3 = mp3url;

    mMediaplayer = new MediaPlayer();
    mMediaplayer.setDataSource(mp3);
    mMediaplayer.prepare();//prepare to play
    if (mMediaplayer.isPlaying()) {
        stopPlaying();
    } else {
        playMedia();
    }



}

private void stopPlaying() {

    if (mMediaplayer != null) {
        mMediaplayer.stop();
    }
}


private void playMedia() {

        mMediaplayer.start();
    }
}

然后在项目onclick

 try {
         fetchAudioUrlFromFirebase();
      } catch (IOException e) {
      e.printStackTrace();
      }

问题:假设媒体播放器已经在播放

// song is playing
mMediaplayer = new MediaPlayer(); // you created a new player
mMediaplayer.setDataSource(mp3);
mMediaplayer.prepare();//prepare to play
if (mMediaplayer.isPlaying()) { // new player is not in playing state
    stopPlaying();              // so you always checking the state of new player
} else {
    playMedia();
}

先检查再创建

if (mMediaplayer!=null && mMediaplayer.isPlaying()) {
    stopPlaying();
} 
mMediaplayer = new MediaPlayer();
mMediaplayer.setDataSource(mp3);
mMediaplayer.prepare();//prepare to play
playMedia();

所以逻辑可以简化为

if (mMediaplayer!=null && mMediaplayer.isPlaying()) {
    mMediaplayer.stop();
    mMediaplayer.release();
} 
mMediaplayer = new MediaPlayer();
mMediaplayer.setDataSource(mp3);
mMediaplayer.prepare();//prepare to play
mMediaplayer.start();