Help! Problem with Sound Library not playing properly

I am very new with this so please bare with me
I am doing an exercise which involves using two libraries, so the idea is doing something with a video and them play a song. I starts fine but when it gets to the song it plays really slowly, gets stuck and makes weird noises.

< import processing.sound.;
SoundFile file;
import processing.video.
;
Capture cam;
int switcher = 0;

void setup() {
size (640,480);
cam=new Capture (this, 640,480);
cam.start();
}
void draw(){

tint(256, 256, 256);
background(0);

if (cam.available()){
cam.read();
}
if(switcher==0){
image (cam,0,0);
}

else if(switcher==1){
scale (-1,1);
image (cam,-width,0);
}
else if(switcher == 2){
scale (-1,-1);
image (cam,-width,-height);
  }
  else if(switcher == 3){

tint(256,0,0);
image(cam,0, 0, width/2, height/2);

tint(0,256,0);
image(cam, width/2, 0, width/2, height/2);

tint(0, 0, 256);
image(cam, 0, height/2, width/2, height/2);

tint(256, 0, 256);
image(cam, width/2, height/2, width/2, height/2);   

file=new SoundFile(this, "Colocao.mp3");
file.play();
  }

  else if(switcher==4){
    image(cam, mouseX,mouseY,width/2,height/2);
    
       }  
  else {
    println ("Switcher = 0 again");
    switcher=0;
    file.stop();
  }

}
void mousePressed(){
switcher ++;

  }>

Welcome. It’s always helpful to post what version of Processing your are using and what OS you run. Cheers.

Hi @Flor_st. The problem is most likely because you are both loading and playing back the sound file in the draw loop. This will load and playback your file at the framerate, so perhaps up to 30-60 times per second, which is why you’re hearing the distortion.
Instead you should use the isPlaying() method:

import processing.sound.*;
SoundFile soundfile;

void setup() {
  size(640, 360);
  background(255);

  // Load the soundfile in the setup method
  soundfile = new SoundFile(this, "vibraphon.aiff");
}      

void draw() {
  if(!soundfile.isPlaying())
    soundfile.play();
}

Keep in mind the code above will basically loop the file. Good Luck!

1 Like