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

时间:2015-05-29 10:11:41

标签: android android-studio android-mediaplayer audio-player android-music-player

我需要在Android应用程序中播放音频,因此我使用了MediaPlayer。 我创建了两个按钮:播放和暂停,但在我暂停一首歌并想要恢复它之后,歌曲再次开始,而不是从我离开的地方恢复。

我写了这段代码:

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

}

怎么了?

2 个答案:

答案 0 :(得分:1)

每次调用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);

}

答案 1 :(得分:0)

你的问题在playPre(View view)转发,试试这个:

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

您还需要检查媒体是否已播放 mediaPlayer.isPlaying()

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