0

I'm very new to coding and it's my first time asking something on Stack Overflow!

I'm trying to play 3 different sound files at 3 different conditions: when waist angle is < 195, the sound file "high" should play, and the two others should not play, etc.

I'm using import processing.sound.*; and have declared the sound files in the void setup().

The problem is that the angle of waist is getting constantly updated, therefore the sound file starts multiple times and crashes.

Could anyone help me with this?

if (waist != null){
       if(waist.angle<195){
          text("waist too high", waist.getCenter().x, waist.getCenter().y);
           low.stop();
           correct.stop();
           high.play();
       } else if(waist.angle>205){
         text("waist too low", waist.getCenter().x, waist.getCenter().y);
           high.stop();
           correct.stop();
           low.play();
       } else text("you're doing well", waist.getCenter().x, waist.getCenter().y);
           high.stop();
           low.stop();
           correct.play();
     }
  • How long are the sounds? Try sleeping the thread while the sound is playing before continuing to the next iteration. – crunchy May 11 '18 at 12:02
  • What framework/libraries are you useing to play sounds? – betontalpfa May 11 '18 at 12:03
  • 1
    You can get the length of the audio file based on the following post: https://stackoverflow.com/a/3009973/2506522 Then you can stop the thread for the given time. – betontalpfa May 11 '18 at 12:07
  • In addition to @betontalpfa's comment (using `duration()` to check for your run length, as per the [documentation for the library you're using](https://processing.org/reference/libraries/sound/SoundFile.html)), you could also use `loop()` vs. `play()`, and only call `loop()` if it is not the currently running `SoundFile` (track this with a variable) (IE: replace `high.play()` with `if (playing != high) { playing = high; high.loop(); }`, as a quick and dirty approach). You have options here. – Ironcache May 11 '18 at 12:12
  • Keeping track of what's currently playing would also allow you to do away with excess `stop()` calls (IE: instead of call `stop()` on `low` and `correct` when you want to play `high`, you can just call it on what is currently `playing`). – Ironcache May 11 '18 at 12:19

1 Answers1

0

You should make a rate-limit for your function.

Suppose you wrapped your function to playSound(waist) which take a waist instance and play/stop sound crrectly.

Then you could be able to limit its call rate by a simple timer like this:

long lastTimestamp = 0; // Init this in your void setup() or in your constructor
static final THRESHOLD = 2000; // Process event at most once per 2s

And in your event processor:

long currentTimestamp = System.currentTimeMillis();
if (currentTimestamp - lastTimestamp >= THRESHOLD) {
   // Process the event
   playSound(waist);
} 
Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51