xxxxxxxxxx
118
//first mouseclick on the canvas, press key 'a' to toggle play ambient sound
//when ambient is on, hold down mouse to play noise
//move mouse across screen to change the frequency of signal
var ambient;
var signal;
var fft, noise, filter;
var res = 5; //can change size of squares, has to be >3
var aPressed = false;
function preload() { // Load sound first before setup is called
ambient = loadSound('sounds/ambient.wav');
signal = loadSound('sounds/signal.wav');
}
function setup() {
createCanvas(640, 360);
background(220);
frameRate(30);
//borrowed from reference:https://p5js.org/reference/#/p5.Filter
filter = new p5.BandPass();
fft = new p5.FFT();
noise = new p5.Noise();
// disconnect unfiltered noise,
// and connect to filter
noise.disconnect();
noise.connect(filter);
noise.start();
}
function draw() {
// set the BandPass frequency based on mouseX
var freq = map(mouseX, 0, width, 20, 10000);
filter.freq(freq);
// give the filter a narrow band (lower res = wider bandpass)
filter.res(50);
//when a is pressed, display greyscale grids, trigger play ambient
if (aPressed === true) {
for (x = 0; x < width; x = x + res) {
for (y = 0; y < height; y = y + res) {
noStroke();
if (mouseIsPressed) {
fill(random(0, 255), random(0, 255), random(0, 255));
} else {
fill(random(0, 255));
}
rect(x, y, res, res);
}
}
}
//when mouse is within the canvas, draw greyscale slider trigger play noise
for (i = 0; i < width; i = i + res) {
var distance = abs(map(mouseX - i, 0, 640, 0, 255));
noStroke();
if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) {
//???only happens when a is pressed, slider stays even when mouse is out of canvas
fill(distance, 150);
} else {
fill(distance, 0);
}
rect(i, 0, res, height);
}
isMouseOverCanvas();
}
//press key a to toggle play ambient
function keyPressed() {
if (key === 'a') {
if (!ambient.isPlaying()) {
ambient.loop();
console.log(key)
} else if (ambient.isPlaying()) {
ambient.stop();
console.log(key)
}
}
aPressed = !aPressed;
}
//hold down mouse to play signal
function mousePressed() {
if (aPressed === true) {
signal.setVolume(0.5);
signal.loop();
console.log("mousepressed");
}
}
function mouseReleased() {
if (aPressed === true) {
signal.stop();
}
}
//when mouse is within canvas, produce noise
function isMouseOverCanvas() {
if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) {
noise.amp(0.5, 0.2);
} else {
noise.amp(0, 0.2);
}
}