My activity plays a specific sound effect once every second.
The following code works, however there is a bug: occasionally the sound is played TWICE every second. This only happens every once in a while (once every 10-20 attempts). When it happens, the double sound occurs for the entire run of the activity, start to finish. So, if I see the activity started without the bug, it stays that way for the entire run of the activity.
Here’s the relevant code – what’s the problem with it? Thank you!
private Handler mHandler = new Handler();
@Override
protected void onResume() {
super.onResume();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.post(mUpdateTimeTask);
}
@Override
protected void onPause() {
// Another activity is taking focus (this activity is about to be "paused").
mHandler.removeCallbacks(mUpdateTimeTask);
super.onPause();
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
PlayTick();
mHandler.removeCallbacks(this);
mHandler.postDelayed(this, 1000);
}
};
public void PlayTick() {
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
soundPool.play(soundID, volume, volume, 1, 0, 1f);
}
Found a solution – seems it’s a known SoundPool bug, it sometimes plays the effect twice. I used a .wav file; converting the file to .ogg seems to resolve the issue.