xxxxxxxxxx
121
let soundfiles = [];
//array to hold the volumes for each track
let volumes = [];
//array to hold the volume destinations, to smoothly fade in and out
let volumeDestinations = [];
let currentHue = 100;
let currentTextHue = 255;
let currentMessage = "";
//all included soundfiles are 120bpm
function preload() {
//load the sound files
for (let i = 0; i < 5; i++) {
let fileName = "sounds/" + i + ".mp3";
print(fileName);
soundfiles[i] = loadSound(fileName);
}
}
function setup() {
createCanvas(600, 600);
colorMode(HSB);
noStroke();
for (let i = 0; i < soundfiles.length; i++) {
soundfiles[i].loop(); // set all the files to loop
soundfiles[i].setVolume(0); // turn the volume down
volumes[i] = 0; // store the volume as all the way down
volumeDestinations[i] = 0; // set are current destination to the same
}
}
function draw() {
background(currentHue, 255, 255);
drawText();
// assume nothing is still playing,
// and then change later if we find something that is playing
let stillPlaying = false;
for (let i = 0; i < soundfiles.length; i++) {
//set volume
// do smoothing and save the new value to the volumes array
volumes[i] = smoothing(volumes[i], volumeDestinations[i]);
//set the volume
soundfiles[i].setVolume(volumes[i]);
//continuously fade volume out
volumeDestinations[i] -= 0.1;
//constrian the fade out to 0
volumeDestinations[i] = constrain(volumeDestinations[i], 0, 1);
//check to see if any sound is still playing
if (volumeDestinations[i] > 0) stillPlaying = true;
}
//if nothing is playing remove the track number on the screen
if (!stillPlaying) {
currentMessage = "";
}
}
//see what section the of the screen the mouse is in
//set the message and play the track
function mouseMoved() {
let track = 0;
if (mouseX < width / 5) track = 1;
else if (mouseX < (width / 5) * 2) track = 2;
else if (mouseX < (width / 5) * 3) track = 3;
else if (mouseX < (width / 5) * 4) track = 4;
else if (mouseX < width) track = 5;
showMessage(track);
changeTracks(track);
}
function showMessage(i) {
currentHue = generateColor(i);
currentTextHue = generateColor(i + 1);
currentMessage = i;
}
//Write instructions to screen.
function drawText() {
push();
textFont("Arial", 14);
textAlign(LEFT, TOP);
fill(currentTextHue, 255, 255);
text("Move mouse horizontally to make sound", 10, 10);
pop();
push();
textFont("Arial", 80);
textAlign(CENTER);
fill(currentTextHue, 255, 255);
text(currentMessage, width / 2, height / 2);
pop();
}
function generateColor(which) {
// account for going below zero, just set to 100
if (which <= 0) {
return 100;
} else {
return (generateColor(which - 1) + 1.61 * 360) % 360;
}
}
function changeTracks(whichTrack) {
//playing only one sound at a time
//but you can easily make files overlap if you want
for (let i = 0; i < soundfiles.length; i++) {
volumeDestinations[i] = 0;
}
volumeDestinations[whichTrack - 1] = 1;
}
//smoothing for fading in and out
function smoothing(current, destination) {
current += (destination - current) * 0.5;
return current;
}