【问题标题】:my mediaplayer starts a new instance instead of stopping我的媒体播放器启动一个新实例而不是停止
【发布时间】:2017-07-16 03:15:30
【问题描述】:

我正在制作一个播放存储在 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();
    }
}

然后在项目中点击

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

【问题讨论】:

    标签: java android android-mediaplayer


    【解决方案1】:

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

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

    【讨论】:

    • 所以我可以摆脱 stopPlaying() 方法中的位
    • 我很高兴能帮上忙,您可以简单地尝试代码的第三部分来摆脱这两个功能,但是稍后当您通过添加新功能来增加更多复杂性时,很容易维护小功能而不是大功能
    • 好的,所以现在它不会启动一个新实例,它会重新启动当前的 mp3。 @Pavneet_Singh
    • 是的,应该这样,所以你想在同一首歌曲的情况下停止歌曲,如果不同则播放另一首歌曲?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多