Search code examples
javatimeraudiodelay

Delay between sound-playings?


i'm building a kind of simple game, it's a red square you can move around with the arrow keys, I made a finish object, it detects when you get in it. Now, I made it so that if the "player" intersects with the "finish-object", it will play a sound, but it will play the sound EVERY tick. I tried Thread.sleep() and wait(), but that made my whole game sleep, and not just the sound-delay. My playsound method:

public void playSound( String filename ) throws IOException{
    InputStream in = new FileInputStream(filename);
    AudioStream as = new AudioStream(in);
    AudioPlayer.player.start(as);
}

and my playerfinishing intersecting:

        //PLAYER1 LEVEL FINISHING
    if( player.getBounds().intersects(levelfinish.getBounds())){
        message = "A winner is you!";
        try {
            playSound("D:/BadGame/Sounds/winner.wav");
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }

message is just a string that displays in the middle of the screen, it all works, but it needs some kind of delay, so the sound won't play constantly but like after each 10 seconds, or only when you intersect with it, one time. Can you guys give me any clue on how to do this? Thanks!


Solution

  • The reason the sound continues to play is because the conditions are still true every tick. The intersection is still valid after the sound is done, therefore the sound will play again.

    A very simplistic way to prevent the repetition this is to use a variable to keep track of if you have played the sound. Something like this, although this is untested:

    Put this part somewhere that won't get changed every tick:

    boolean soundPlayed = false;
    

    Use this part in your function

     //PLAYER1 LEVEL FINISHING
     if( player.getBounds().intersects(levelfinish.getBounds())){
            message = "A winner is you!";
            if (soundPlayed == false) {
                try {
                   playSound("D:/BadGame/Sounds/winner.wav");
                   soundPlayed = true;
                } catch(Exception ex){
                    ex.printStackTrace();
                }
            }
        }