Using ellipse as button to play sound file?

Hi all, I’m new to p5.js (and a pretty rusty at JavaScript!) and working on building a little program that will have buttons on a map that will play sounds recorded at those points on the map.

I’m attempting to use an ellipse shape as those buttons, but struggling to get it to play the audio. Any advice on how to get that to work? I may have this set up all wrong, but here’s my code. Thank you so much!

var sounds = [];
var bg;
// datapoints are [x, y, mp3Location]
var dataPoints = {
  0: [40, 150, 'assets/crow.wav'],
  1: [32, 77, 'assets/flamingo.wav'],
  2: [255, 255, 'assets/ocelot.wav']
}
var dataPointsLen = Object.keys(dataPoints).length;

function preload() {
  soundFormats('wav');
  for (let i = 0; i < dataPointsLen; i++) {
    let sound = 'sound';
    let thisFile = dataPoints[i][2];
    sounds.push(sound.concat(String(i)));
    sounds.i = loadSound(thisFile);
  }
}

function setup() {
  bg = loadImage('assets/HAlCuTaAu-141.jpg');
  radius = 20;
  createCanvas(1440, 960);
  button = new PlayButton(dataPoints[0][0], dataPoints[0][1], radius, sounds[0]);
}

function draw() {
  background(bg);
  button.display();
}

//create PlayButton object that takes coordinates, radius, soundFile location
function PlayButton(tempX, tempY, radius, soundFile) {
  this.x = tempX;
  this.y = tempY;
  this.diameter = radius*2;

  this.sound = soundFile;
  
  if (mouseIsPressed) {
    if (this.sound.isPlaying()){
      this.sound.stop();
    }
    else{
      this.sound.play();
    }
  }
  
  this.display = function() {
    fill(0,255,0);
    ellipse(this.x, this.y, this.diameter, this.diameter);
  }
}
1 Like

Hi @msugar, welcome.

What part are you stuck on? Have you tried the basic play sound example and gotten it to work?

https://p5js.org/examples/sound-load-and-play-sound.html

Or is it the collision with a button that is difficult? Or the ellipse shape specifically? (That is one of the worst shapes for collision detection – squares and circles are much easier).

Hi Jeremy, indeed I got that example you linked to work. I’m having trouble making the button actually play the sound.

I tried making it a circle and a square instead and still no luck! I’m not sure if it’s actually collision detection or that the .isPlaying(), .play(), and .stop() functions are not working inside of the PlayButton object I built.

Just wanted to mark this resolved! In case anyone reading this in the future is wondering, the above code wasn’t loading the sound files correctly.

I fixed this by taking the file paths out of the ‘dataPoints’ dict and creating a separate ‘soundFiles’ array that I then iterated through to load all the files properly.

1 Like