Interaction Design WikiProgramming

p5.js Sound

p5.sound extends p5 with Web Audio functionality including audio input, playback, analysis and synthesis. In order to work with audio you need to download a javascript library here. The p5.SoundFile may not be available immediately because it loads the file information asynchronously.
Link to online demo

let sound1;
let sound2;

function preload() {
  soundFormats('mp3', 'ogg');
  sound1 = loadSound('doorbell.mp3');
	sound2 = loadSound('cowbell.mp3');
}

function setup() {
  createCanvas(600, 300);

}

function draw() {
  background(100);
  noStroke();
  fill (255);
  ellipse(400, height/2, 40, 40);
  fill (125);
  ellipse(200, height/2, 40, 40);	
}

function mousePressed() {
  //circle 1
  if (overCircle(200, height/2, 40)) {
    print("circle 1");
		doorBell();
  }
  //circle 2
  if (overCircle(400, height/2, 40)) {
    print("circle 2");
    cowBell();
  }
}

function overCircle( x, y,  diameter) {
  //check if mouse is over the circle 
  if (dist(x, y, mouseX, mouseY) <= diameter) {
		 return true;
  } else {
    return false;
  }
}

function doorBell() {
  //toggle sound on and off
  if (sound1.isPlaying() )
  {
    sound1.stop();
		
  } else {
    sound1.play();
		sound2.stop();
  }
}

function cowBell() {
  //toggle sound on and off
  if (sound2.isPlaying() )
  {
		
    sound2.stop();
  } else {
    sound2.play();
		sound1.stop();
  }
}

boolean overCircle(int x, int y, int diameter) {
  //check if mouse is over the circle 
  if (dist(x, y, mouseX, mouseY) <= diameter) {
    return true;
  } else {
    return false;
  }
}

void jukeBox() {
  //toggle sound on and off
  if ( sound1.isPlaying() )
  {
    sound1.pause();
  } else  {
    sound1.play();
  }
  // if the player reaches the end of the file, play the file again
  if ( sound1.onEnded() )
  {
    sound1.play();
  } 
}