xxxxxxxxxx
72
/*
Click on canvas to enable sound playback
Press LEFT ARROW for amplitude from Sound 1
Press RIGHT ARROW for amplitude from Sound 2
Thunder https://freesound.org/people/Erdie/sounds/24003/
Bird Chirp https://freesound.org/people/InspectorJ/sounds/416529/
https://p5js.org/reference/#/p5.FFT
https://p5js.org/reference/#/p5.FFT/analyze
*/
let birdSnd;
let thunderSnd;
// variable for FFT object
let fft;
function preload() {
birdSnd = loadSound('assets/bird.mp3');
thunderSnd = loadSound('assets/thunder.mp3');
}
function setup() {
createCanvas(400, 400);
noStroke();
// create FFT object
fft = new p5.FFT();
}
function draw() {
background(0, 30);
// STEP 1
// get amplitude values by frequency
// analyze() returns an array of values between 0,255
// the default length of the array is 1024
// the array values indicate applitude at individual
// frequences in the human audible range
let analyzeArray = fft.analyze();
// console.log(analyzeArray)
// STEP 2
// map those values to an animation
for (let i = 0; i < analyzeArray.length; i++) {
let x = map(i, 0, analyzeArray.length, 0, width);
let y = map(analyzeArray[i], 0, 255, height, 0);
circle(x, y, 5)
}
}
function keyPressed() {
console.log('key pressed');
if (keyCode === LEFT_ARROW) {
console.log('thunder');
// set fft input to sample
fft.setInput(thunderSnd);
thunderSnd.play();
birdSnd.stop();
}
if (keyCode === RIGHT_ARROW) {
console.log('bird');
// set fft input to sample
fft.setInput(birdSnd);
thunderSnd.stop();
birdSnd.play();
}
}