在我的秒表应用程序中,我有一个开始按钮来启动声音,还有一个暂停按钮来停止或暂停声音。
如果仅按下开始按钮一次,声音的开始和暂停工作正常,那么通过按暂停可以很好地停止声音太
但是多次按开始按钮时会出现问题。我按下开始按钮越多,声音就越快。然后 PAUSE 按钮永远不会停止声音。所以,这是一个错误!导致这种情况的原因以及如何在我的代码中解决它?
[注意:只有在多次点击START按钮时才会出现问题]
public class MainActivity extends Activity {
private Button startButton;
private Button pauseButton;
private Button resetButton;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
mp.setLooping(true);
}
});
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
mp.stop();
}
});
resetButton = (Button) findViewById(R.id.reset);
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timerValue.setText("" + 00 + ":"
+ String.format("%02d", 00) + ":"
+ String.format("%03d", 00));
startTime = SystemClock.uptimeMillis();
timeSwapBuff = 0;
}
});
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
};
}
答案 0 :(得分:1)
在停止按钮中尝试此代码。
if(mp.isPlaying())
{
mp.stop();
mp.reset();
}
如果您想暂停媒体播放器
if(mp.isPlaying())
{
mp.pause();
}