Stop sound looping / echoing in if/else statement

Help! I am working on CSD Unit 3 Lesson 18, creating an interactive card. I have an if/else statement inside the draw loop and want to play a sound when the mouse is down but I want the sound to stop when the mouse is not down. When I put the sound in the loop, and stop it in the else section, it does what I want, but it echoes and is awful to hear. When I put the sound outside of the draw loop, it plays correctly, but won’t stop. Any insight would be much appreciated!!

The reason it echoes like that is because playSound() always begins a new sound, so putting it in the draw loop means it starts the music from the beginning, 30 times a second. A trick to get around this is putting in a variable that is toggled on and off to determine when to play music. Try putting this at the beginning of your program:

var musicPlaying = false;

Then replace your playSound() function with this:

if (!musicPlaying) {
  playSound("Happy_birthday_to_you_MIDI(chosic.com).mp3");
  musicPlaying = true;
}

And finally, put this right after the stopSound() function:

musicPlaying = false;

Now the music will only play if playSound() has not already been called, so the music won’t repeat on itself.

2 Likes

This worked!! I didn’t see the “!” at first in if (!musicPlaying), but once I realized that, tried it and it’s good now. Thank you so much!!