我正在播放暂停播放音频的问题,我想在一个播放按钮中执行三个功能。如果最初按下按钮意味着音频应该播放。如果第二次按下播放按钮意味着音频应该暂停并再次按下按钮意味着音频应该从暂停状态恢复。我尝试了许多方法,我可以暂停音频,但它再次从正在播放而不是从暂停状态恢复音频。
我使用了这个条件 if(!mediaPlayer.isPlaying()&& mediaPlayer.getCurrentPosition()> 0)
but it is not working.
我的工作代码是
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(activity, "Playing sound", Toast.LENGTH_SHORT).show();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
if( !mediaPlayer.isPlaying() && mediaPlayer.getCurrentPosition() > 0 ){
long currentPosition = mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo((int) currentPosition);
mediaPlayer.start();
}
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.setOnPreparedListener((MediaPlayer.OnPreparedListener) activity);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
finalTime = mediaPlayer.getDuration();
startTime = mediaPlayer.getCurrentPosition();
if (oneTimeOnly == 0) {
seekBar.setMax((int) finalTime);
oneTimeOnly = 1;
}
songEndTime.setText(String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours((long) finalTime),
TimeUnit.MILLISECONDS.toMinutes((long) finalTime) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours((long) finalTime)), // The change is in this line
TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime))));
songStartTime.setText(String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours((long) startTime),
TimeUnit.MILLISECONDS.toMinutes((long) startTime) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours((long) startTime)),
TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime))));
seekBar.setProgress((int) startTime);
myHandler.postDelayed(UpdateSongTime, 100);
stop.setVisibility(View.VISIBLE);
play.setVisibility(View.GONE);
}
});
答案 0 :(得分:0)
mediaPlayer.pause();
length = mediaPlayer.getCurrentPosition();
并且从最近停止的位置恢复玩家是通过以下方式完成的:
mediaPlayer.start();
mediaPlayer.seekTo(length);
答案 1 :(得分:0)
首先设置MediaPlayer数据源,然后删除“mediaPlayer.reset();” 因为每次单击按钮时都会重置MediaPlayer对象。 这就是为什么它总是从头开始的原因。