Reputation: 49
I have a CountDownTimer which is 10 seconds long. I want to play a sound when half of the time is past on the timer. I can play sound but the problem is the audio is played twice.
Think that this is the sound I want to play: "Hi how are you."
It plays like this: "Hi Hi how are you.".
The playAudio() plays correct when it is not inside the onTick() method. It has something with the if(seconds == 5). I don't know what.
public class RestCountDownTimer extends CountDownTimer {
public RestCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
@Override
public void onFinish() {
if(txtRestTime != null){
if(finishSound != 0){
sp.play(finishSound, 1, 1, 0, 0, 1);
}
displayImage();
}
}
@Override
public void onTick(long millisUntilFinished) {
if(txtRestTime != null){
long seconds = (millisUntilFinished+1000) / 1000;
txtRestTime.setText("" + seconds);
if(seconds == 5){
playAudio(audio);
}
}
}
}
Upvotes: 1
Views: 1141
Reputation: 49
Because my CountDownTimer was initialized like this I got the problem.
restCountDownTimer = new RestCountDownTimer(30000, 500);
If my interval would be 1000 I would not get the problem.
This is how I solved it. I created a boolean state variable to check if the sound is played once or not. If the sound is played then skip it next time.
public class RestCountDownTimer extends CountDownTimer {
private boolean stateAudio = false;
public RestCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
@Override
public void onFinish() {
if(txtRestTime != null){
if(finishSound != 0){
sp.play(finishSound, 1, 1, 0, 0, 1);
stateAudio = false;
}
displayImage();
}
}
@Override
public void onTick(long millisUntilFinished) {
if(txtRestTime != null){
long seconds = (millisUntilFinished+1000) / 1000;
txtRestTime.setText("" + seconds);
if((seconds == 5) && (stateAudio == false)){
playAudio(audio);
stateAudio = true;
}
}
}
}
Upvotes: 1
Reputation: 1649
Try adding some logging, and see if your onTick millisUntilFinished is being called more often than you think. It's possible that it's being called e.g. at 5 seconds and at 5.5 seconds, both of which would generate a "seconds" variable of 5. You might either want to tweak the interval you're using, or else save a boolean soundPlayed and don't play again if it's set.
Upvotes: 1