We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Going to keep this basic. I have an array of 10 sounds. Sometimes, I want to play a random sound out of the ones in the array, however I don't want the same sound to play twice at the same time.
For reasons hard to explain, at the time being, I can't test my code. However I will Monday and I'd like to know if this is OK by then so I can tackle other issues on Monday:
playSound()
{
int sndRdm = int(floor(random(0, snds.length)));
if (snds[sndRdm].isPlaying()) {
playSound();
}
else {
snds[i].play();
}
}
Answers
Better to avoid recursion - this will do what you want
Basically the do-while continues to calculate a random index position in the array repeatable until it gets one that is not playing. Then it will play the selected song.
You do not need the
floor()
method sincerandom(a, b)
returns a number in the range>=a
and<b
so theint()
method returns an integer in the rangea
tob-1
This 1 also works ->
sndRdm = (int) random(snds.length);
~O)Also, invoking playSound() as a separate Thread would allow your program to do other tasks in parallel: (*)
There is no need to invoke playSound() in a separate Thread because the play() method simply starts the music and then exits, so the execution time of this method is miniscule, especially compared with the time for Java to setup the thread. The only problem here is if the array length is 1 in which case the loop will continue until the sound has finished playing.
So putting it all together we get
:-h
Hey, thanks a lot for the insight! :)