xxxxxxxxxx
88
/*
https://p5js.org/reference/#/p5.Envelope
https://p5js.org/reference/#/p5.Envelope/setADSR
*/
let osc;
let fft;
let env;
// ADSR Envelope Variables
let attackLevel = 0.5;
let releaseLevel = 0;
let attackTime;
let decayTime;
let sustainRatio;
let releaseTime;
function setup() {
createCanvas(400, 400);
env = new p5.Envelope()
// create an oscillator
osc = new p5.Oscillator('sine');
// set the frequency to 330Hz
// near the musical note E above middle C
osc.freq(330);
osc.amp(env);
// create a FFT object to visualize the sound
fft = new p5.FFT();
fft.setInput(osc);
}
function draw() {
background(0);
attackTime = map(mouseX, 0, width, 0, 2);
// decayTime = 0.5;
decayTime = map(mouseY, 0, height, 0, 2);
// sustainRatio = 0.5;
sustainRatio = map(mouseX, 0, height, 0, 1);
// releaseTime = 0.5;
releaseTime = map(mouseY, 0, height, 0, 2);
// Visualize the sound's waveform
let waveform = fft.waveform();
beginShape();
noFill();
stroke(255);
for (let i = 0; i < waveform.length; i++) {
let x = map(i, 0, waveform.length, 0, width);
let y = map(waveform[i], -1, 1, height, 0);
vertex(x, y);
}
endShape();
// write values on the canvas
textSize(16);
fill(255);
text(`fade up - attackTime: ${attackTime}`, 10, 320);
text(`fade down - decayTime: ${decayTime}`, 10, 340);
text(`sustain - sustainRatio: ${sustainRatio}`, 10, 360);
text(`fade to release level - releaseTime: ${releaseTime}`, 10, 380);
}
function mousePressed() {
// start oscillator to enable audio
osc.start();
env.setRange(attackLevel, releaseLevel);
env.setADSR(attackTime, decayTime, sustainRatio, releaseTime)
env.play(osc);
}
function mouseReleased() {
osc.stop();
}