xxxxxxxxxx
144
let osc;
let playing = false;
let dots = [];
let time = 0;
let lowFreq = 100;
let highFreq = 2000;
let sliderWidth = 200;
let sliderX = 10;
let sliderY = 50;
let lowHandleX = sliderX;
let highHandleX = sliderX + sliderWidth;
let draggingLow = false;
let draggingHigh = false;
function setup() {
createCanvas(400, 400);
osc = new p5.Oscillator('sine');
}
function draw() {
background(200);
// Dual-end Slider
stroke(0);
line(sliderX, sliderY, sliderX + sliderWidth, sliderY);
fill(0);
ellipse(lowHandleX, sliderY, 10);
ellipse(highHandleX, sliderY, 10);
// Update Frequency Range
lowFreq = map(lowHandleX, sliderX, sliderX + sliderWidth, 100, 2000);
highFreq = map(highHandleX, sliderX, sliderX + sliderWidth, 100, 2000);
text(`Frequency Range: ${int(lowFreq)} Hz to ${int(highFreq)} Hz`, 10, 20);
// Draw C notes based on the range
for (let f = lowFreq; f <= highFreq; f *= pow(2, 1 / 12)) {
if (round(f) % 100 === 0) {
let x = map(f, lowFreq, highFreq, 0, width);
stroke(0, 255, 0);
line(x, 0, x, height);
}
}
let thefreq = map(mouseX, 0, width, lowFreq, highFreq);
let theamp = map(mouseY, height, 0, 0, 1);
// Handle mouse-pressed oscillator
if (mouseIsPressed) {
if (mouseX > width || mouseY > height || mouseX < 0 || mouseY < 0) return;
if (!draggingLow && !draggingHigh) {
if (!playing) {
osc.start();
playing = true;
}
osc.freq(thefreq);
osc.amp(theamp);
}
} else {
if (playing) {
osc.stop();
playing = false;
}
}
let noiseValue = noise(time);
line(0,noiseValue*height,width,noiseValue*height);
// Handle dots
for (let dot of dots) {
fill(100, dot.dynamic? 0 : 200, (dot.y > (noiseValue*height)) ? 0 : 255);
ellipse(dot.x, dot.y, 10, 10);
if (dot.dynamic) {
dot.freq = map(dot.x, 0, width, lowFreq, highFreq);
}
let dotNoise = noise(dot.id);
if (noiseValue > dot.y/height) {
dot.osc.freq(dot.freq);
dot.osc.amp(dot.amp);
if (!dot.playing) {
dot.osc.start();
dot.playing = true;
}
} else {
if (dot.playing) {
dot.osc.stop();
dot.playing = false;
}
}
}
time += 0.01;
}
function mousePressed() {
if (dist(mouseX, mouseY, lowHandleX, sliderY) < 10) {
draggingLow = true;
} else if (dist(mouseX, mouseY, highHandleX, sliderY) < 10) {
draggingHigh = true;
}
}
function mouseReleased() {
draggingLow = false;
draggingHigh = false;
}
function mouseDragged() {
if (draggingLow) {
lowHandleX = constrain(mouseX, sliderX, highHandleX);
} else if (draggingHigh) {
highHandleX = constrain(mouseX, lowHandleX, sliderX + sliderWidth);
}
}
function keyPressed() {
let newOsc = new p5.Oscillator('sine');
let thefreq = map(mouseX, 0, width, lowFreq, highFreq);
let theamp = map(mouseY, height, 0, 0, 1);
let newDot = {
x: mouseX,
y: mouseY,
freq: thefreq,
amp: theamp,
osc: newOsc,
playing: false,
id: random(1000),
dynamic: false
};
if (key === 'D' || key === 'd') {
newDot.dynamic = true;
} else if (key === 'S' || key === 's') {
newDot.dynamic = false;
} else {
return;
}
dots.push(newDot);
}