Android MediaPlayer pause() 停止播放器并重新开始

Android MediaPlayer pause() stops the player and start again

我需要在 Android 应用程序中播放音频,所以我使用了 MediaPlayer。 我创建了 2 个按钮:播放和暂停,但在我暂停一首歌曲并想继续播放之后,歌曲又开始播放,而不是从我离开的地方继续播放。

我写了这段代码:

public MediaPlayer mediaPlayer = new MediaPlayer();


public void playPre(View view) {
    //mediaPlayer.release();
    mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.music);
    mediaPlayer.start(); 
    ImageView pausaOneButton = (ImageView)findViewById(R.id.PausaOneButton);
    pausaOneButton.setVisibility(View.VISIBLE);


}

public void stopPre(View view) {

    mediaPlayer.pause();
    ImageView pausaOneButton = (ImageView)findViewById(R.id.PausaOneButton);
    pausaOneButton.setVisibility(View.INVISIBLE);

}

怎么了?

您在每次调用 playPre() 时重新创建 MediaPlayer。您可以将代码更改为:

public MediaPlayer mediaPlayer = null;

public void playPre(View view) {
    if (mediaPlayer == null) {
        mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.music);
    }
    mediaPlayer.start(); 
    ImageView pausaOneButton = (ImageView)findViewById(R.id.PausaOneButton);
    pausaOneButton.setVisibility(View.VISIBLE);


}

public void stopPre(View view) {

    mediaPlayer.pause();
    ImageView pausaOneButton = (ImageView)findViewById(R.id.PausaOneButton);
    pausaOneButton.setVisibility(View.INVISIBLE);

}

您的问题在 playPre(View view) 中中继,试试这个:

if(mediaPlayer == null) {
  mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.fire);
}
if(mediaPlayer.isPlaying()){
  return;
}
mediaPlayer .start();

您还必须检查媒体是否已经在播放mediaPlayer.isPlaying()

这是我为媒体播放器制作的示例项目: Test Project