xxxxxxxxxx
100
// Constants
const WAVEFORM = true;
const SPECTRUM = false;
const OSC_MIN = 100;
const OSC_MAX = 1000;
const FIL_MIN = 100;
const FIL_MAX = 1000;
// Globals
let playing;
// Setup
function setup() {
// Create canvas, register mouse pressed event
let cnv = createCanvas(windowWidth, windowHeight);
cnv.mousePressed(playOscillator);
// Set up Fast Fourier Transform for waveform analysis
fft = new p5.FFT(0.8, 1024);
// Create effect, filter, and oscillator and connect them
rev = new p5.Reverb();
lp = new p5.LowPass();
osc = new p5.Oscillator('sawtooth');
osc.disconnect();
osc.connect(rev);
rev.disconnect();
rev.connect(lp);
}
// Draw loop
function draw() {
// Set background
background(220);
// Constrain and map mouse input to oscillator and low pass frequency
osc_freq = constrain(map(mouseX, 0, width, OSC_MIN, OSC_MAX), OSC_MIN, OSC_MAX);
lp_freq = constrain(map(mouseY, height, 0, FIL_MIN, FIL_MAX), FIL_MIN, FIL_MAX);
// Draw text on top left corner
fill('#000000');
text('tap to play', 20, 20);
text('oscillator frequency: ' + osc_freq.toFixed(2), 20, 40);
text('low pass frequency: ' + lp_freq.toFixed(2), 20, 60);
text('playing: ' + playing, 20, 80);
// Grab FFT waveform and draw across Canvas
if (WAVEFORM) {
let waveform = fft.waveform();
noFill();
beginShape();
stroke(20);
for (let i = 0; i < waveform.length; i++) {
let x = map(i, 0, waveform.length, 0, width);
let y = map(waveform[i], -1, 1, 0, height);
circle(x, y, 2);
}
endShape();
}
if (SPECTRUM) {
let spectrum = fft.analyze();
noStroke();
for (let i = 0; i< spectrum.length; i++){
let x = map(i, 0, spectrum.length, 0, width);
rainbowFill(x);
let h = -height + map(spectrum[i], 0, 255, height, 0 + (height / 2));
rect(x, height, width / spectrum.length, h);
}
}
// If synth playing (mouse held) set oscillator and low pass frequency to constrain/mapped values
if (playing) {
// smooth the transitions by 0.1 seconds
osc.freq(osc_freq, 0.1);
lp.freq(lp_freq, 0.1);
}
}
function playOscillator() {
// Set oscillator amplitude to 1, start oscillator, and update playing variable
osc.amp(1);
osc.start();
playing = true;
}
function mouseReleased() {
// Set oscillator amplitude to 0, and update playing variable
osc.amp(0);
playing = false;
}
function rainbowFill(x) {
let z = map(x, 0, width, 0, 2 * PI);
let r = 255 * sin(z + (PI / 2)) + 255;
let g = 255 * sin(z + (7 * PI / 6));
let b = 255 * sin(z + (11 * PI / 6)) + 255;
fill(r, g, b);
}