Multiple Volume Controls on Multiple Sound Files

Hello!

I’m fairly new to p5.js and am trying to create a very simple audio crossfader that allows you to listen to 2 sound files at once, and control the mix by moving the mouse along the X axis.

I am getting stuck when I try to apply 2 volume controls to 2 seperate sound files within the same sketch. Code is below – I’m sure I’m missing something really obvious here, but am also just concerned that perhaps p5.js is limited in it’s ability to control volume for seperate audio files as opposed to just controlling the master output?

Thanks in advance!


let song;
let song1;

function preload() {
song = loadSound(‘You.mp3’);
song1 = loadSound(‘Me.mp3’);
}

function setup() {
createCanvas(720, 400);
song.loop(); // song is ready to play during setup() because it was loaded during preload
song1.loop(); // song is ready to play during setup() because it was loaded during preload
}

function draw() {
background(230);

let volume = map(mouseX, 0, width, 0, 1);
let volume1 = map(mouseX, 0, width, 1, 0);

volume = constrain(volume, 0, 1);
volume1 = constrain(volume, 0, 1);

song.amp(volume);
song1.amp(volume1);

}

function mousePressed() {
song.play();
song1.play();
background(0, 255, 0);
}

Your issue is with your second volume constrain (typo) …

const NUM_SNGS = 2;
let sngs = [],
  vols = [];

function preload() {
  for (let i = 0; i < NUM_SNGS; i++) {
    sngs[i] = loadSound(`sng${i}.mp3`);
  }
}

function setup() {
  createCanvas(720, 400);

  sngs.forEach(sng => {
    sng.play();
    sng.loop();
  });
}

function draw() {
  background(230);

  vols[0] = map(mouseX, 0, width, 0, 1);
  vols[1] = map(mouseX, 0, width, 1, 0);

  vols.forEach(vol => {
    constrain(vol, 0, 1);
  });
  sngs.forEach((sng, i) => {
    sng.amp(vols[i]);
  });
}