繁体   English   中英

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

[英]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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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