xxxxxxxxxx
74
let pianoKeys = [];
let currentNote;
let synth;
function setup() {
createCanvas(800, 200);
// Create an array of piano keys
for (let i = 0; i < 14; i++) {
let keyWidth = width / 14;
let keyHeight = height * 0.75;
let isBlack = i % 7 == 1 || i % 7 == 4 ? true : false;
let note = isBlack ? '#' : '';
pianoKeys.push({ x: i * keyWidth, y: 0, w: keyWidth, h: keyHeight, isBlack, note });
}
// Initialize the p5.sound synthesizer
synth = new p5.PolySynth();
synth.setADSR(0.02, 0.1, 0.2, 0.5); // Adjust the envelope settings
}
function draw() {
background(240);
// Draw piano keys
for (let key of pianoKeys) {
if (key.isBlack) {
fill(0);
} else {
fill(255);
}
rect(key.x, key.y, key.w, key.h);
}
}
function mousePressed() {
for (let key of pianoKeys) {
if (mouseX >= key.x && mouseX <= key.x + key.w && mouseY >= key.y && mouseY <= key.y + key.h) {
currentNote = key.note;
playSound(currentNote);
}
}
}
function keyPressed() {
if (key === 'a') {
currentNote = 'C4';
playSound(currentNote);
} else if (key === 's') {
currentNote = 'D4';
playSound(currentNote);
} else if (key === 'd') {
currentNote = 'E4';
playSound(currentNote);
} else if (key === 'f') {
currentNote = 'F4';
playSound(currentNote);
} else if (key === 'g') {
currentNote = 'G4';
playSound(currentNote);
} else if (key === 'h') {
currentNote = 'A4';
playSound(currentNote);
} else if (key === 'j') {
currentNote = 'B4';
playSound(currentNote);
}
}
function playSound(note) {
// Play the note with the synthesizer
synth.play(note);
}