Sound files making my code run much slower

Hi,

I’m new to P5 and working on a code for a school project. I have four sound clips in my code but everytime I have them on, the code becomes very visibly slower. I’m using the preload function to load them in, and then they play based on what checkbox is selected. I’m wondering if there is any way around this? Please help!!

Here is the sketch **Type any lower-case letter **

https://editor.p5js.org/achandra/sketches/flm8aL1Xl

1 Like

Welcome to the forums! How big are your sound files?

Around 3.5 MB each. There are 4 of them.

Hello @achandra,

So, I’ll try to answer this with a hand full of questions. :blush:

When running the sketch and checking one of the checkboxes. Does the music sound like you expect it too? For me, it sounds pretty odd compared to the original mp3. Kind of echo-like and spooky. Why is that?

Right now, inside your draw function, you have code like this:

  if(sound01){
    s1.play();
  }

The logic above says, “if the checkbox for sound 1 is checked, play sound 1”. But, what if the sound is already playing? Have you checked out isPlaying()?

3 Likes

Hi @Sven

The sounds does sound a bit stretched out and I havent been able to figure out why that is? Can that be because of the size of my sound files? I tried loading them one at a time to see if it makes a difference, and it still doesn’t make a difference.

I didn’t understand what you mean by “if sound is already playing?”

Right now the code is:

if(sound01){
    s1.play();
  }
  else if(!sound01){
    s1.stop();
  } 

So everytime, you uncheck the box, the sound stops. I tried isPlaying() too like this:

if(sound01){
    s1.play();
  }
  else if(!sound01 && s1.isPlaying()){
    s1.stop();
  } 

but this doesnt seem to be working either!

1 Like

The logic is inside the draw function. draw is called several times per second, depending on the frame rate. Probably around 60 times per second.

When a user interacts with your sketch, she waits for a while and then checks the checkbox. Some milliseconds after that the draw function executes, the logic finds that the checkbox is checked and starts playing the sound. 16 milliseconds after that, the draw function executes again. The checkbox is still checked, so it starts playing the sound again (now two instances of that sound is playing – 16 ms apart). And so it continues.

That’s why it sounds so stretched out. It’s not one instance of the sound playing: it’s hundreds with a little bit delay between them.

So, how do we avoid this cacophony? :slight_smile:

3 Likes

@Sven

Ofcourse! Thanks so much! I added this and I think it fixed the code!:

  if(sound01 && !s1.isPlaying()){
    s1.play();
  }
  
  else if(!sound01 && s1.isPlaying()){
    s1.stop();
  }

The sound doesnt sound echoey and is also not making my code run slower! Yay! Thanks a tonne!

3 Likes