Recursion with minim.

edited October 2013 in Questions about Code

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

  • Answer ✓

    Better to avoid recursion - this will do what you want

    void playSound()  {
        int sndRdm;
        do {
            sndRdm = int(random(0, snds.length));
        } while(snds[sndRdm].isPlaying());
        snds[sndRdm].play();
     }
    

    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 since random(a, b) returns a number in the range >=a and <b so the int() method returns an integer in the range a to b-1

  • edited October 2013

    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: (*)

    thread("playSound");
    
  • 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

    void playSound()  {
        int sndRdm;
        if(snds.length > 1) {
            do {
                sndRdm = (int)random(snds.length);
            } while(snds[sndRdm].isPlaying());
            snds[sndRdm].play();
        }
    }
    

    :-h

  • Hey, thanks a lot for the insight! :)

Sign In or Register to comment.