How to keep music from overlapping

Hi! I have it where if the mouse is clicked inside the rectangle’s bounds then music will play. But every time I click inside the rectangle’s bounds the music will will repeat on top of each other. Is there a way I can get it where additional mouse clicks inside the bounds won’t result in overlapping music? I was thinking maybe there is a way to make the music to play out entirely before an additional mouse click plays the music again. Or if there was a way to make the music just restart if the mouse is clicked in the rectangle’s bounds after the initial click.

import processing.sound.*;
SoundFile file;

void setup() {
  size(500,500);
  file = new SoundFile(this,"music.mp3");
  
}

void draw() {
  fill(0);
  rect(width/2, height/2, 100,75);
}

void mouseClicked() {
  if (mouseX>(width/2) && mouseY>(height/2) && mouseY<(height/2+75) && mouseX<(width/2+100)) {
    file.play();;
  }
}
1 Like

Add in a timer like this :

int timer = 0;

void mouseClicked() {
   if (mouseX.... && millis() > timer) {
      file.play();
      int soundDuration = int(file.duration()*1000);
      timer = millis()+soundDuration;
   }
}
1 Like

@Lexyth gives a good solution here.

Check out the SoundFile reference:

https://processing.org/reference/libraries/sound/SoundFile.html

Use isPlaying() to check if it is playing. If so, use jump() to jump to the beginning of the sound. Or stop() – whatever you want it to do.