When I click the button in the app, it play the sound perfectly. However, the button that trigger start and stop and the back button of the phone is able to click again, but the sound keeps playing. There is no error message show up in both ellipse and the phone.
I know the problem is my program trapped in the for loop of playing the sound. However I don't know how to make it without using an infinity loop if i want to loop it infinity. Any suggestion to fix this?
The sound of this metronome is like tick, tick, tick, tock...... And I want to use the button to trigger the sound.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
final Button button = (Button) findViewById(R.id.startStop);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean start = false;
if (start == false) {
play();
} else if (start == true) {
start = false;
}
}
});
}
public void play() {
final SoundPool sndPool1 = new SoundPool(3, AudioManager.STREAM_MUSIC,
0);
final SoundPool sndPool2 = new SoundPool(3, AudioManager.STREAM_MUSIC,
0);
final int ticks = sndPool1.load(this, R.raw.tick, 1);
final int tocks = sndPool2.load(this, R.raw.tock, 1);
for (;;) {
sndPool2.play(tocks, 1f, 1f, 1, 0, 1f);
LockSupport.parkNanos(((240000 / 200) / 4) * 1000000);
sndPool2.play(tocks, 1f, 1f, 1, 0, 1f);
LockSupport.parkNanos(((240000 / 200) / 4) * 1000000);
sndPool2.play(tocks, 1f, 1f, 1, 0, 1f);
LockSupport.parkNanos(((240000 / 200) / 4) * 1000000);
sndPool1.play(ticks, 1f, 1f, 1, 0, 1f);
LockSupport.parkNanos(((240000 / 200) / 4) * 1000000);
}
}