xxxxxxxxxx
/**
* Demonstrates cross-fading between two audio tracks.
*
* The sound files are licensed from [Free Music Archive](https://www.freemusicarchive.org/)
* Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) license.
* - Points of no Return (ID 1285) by Lobo Loco
* - Country Boy - Instrumental (ID 1348) by Lobo Loco
*/
let track1, track2;
let env1, env2;
function preload() {
track1 = loadSound("country_boy.m4a");
track2 = loadSound("points_of_no_return.m4a");
}
function setup() {
createCanvas(windowWidth, windowHeight);
// 5 seconds to fade in (attack), 3 seconds to fade out (release)
env1 = new p5.Envelope(5, 1, 0, 1, 3, 0);
env1.setInput(track1);
env2 = new p5.Envelope(5, 1, 0, 1, 3, 0);
env2.setInput(track2);
}
function draw() {
background(200);
textAlign(CENTER, CENTER)
noStroke();
textSize(20);
let isPlaying1 = track1.isPlaying() && env1.wasTriggered;
fill(isPlaying1 ? 'green' : 0);
rect(0, 0, width / 2, height)
fill(200);
text(`Click to ${isPlaying1 ? "Stop" : "Play"} track #1`, width / 4, 50);
let isPlaying2 = track2.isPlaying() && env2.wasTriggered;
fill(isPlaying2 ? 'green' : 0);
rect(width / 2, 0, width / 2, height)
fill(200);
text(`Click to ${isPlaying2 ? "Stop" : "Play"} track #2`, width * 3 / 4, 50);
}
function mousePressed() {
if (mouseX < width / 2) {
if (track1.isPlaying() && env1.wasTriggered) {
env1.triggerRelease();
} else {
track1.play();
env1.triggerAttack();
if (track2.isPlaying()) {
env2.triggerRelease();
}
}
} else {
if (track2.isPlaying() && env2.wasTriggered) {
env2.triggerRelease();
} else {
track2.play();
env2.triggerAttack();
if (track1.isPlaying()) {
env1.triggerRelease();
}
}
}
}