xxxxxxxxxx
56
// Set the frequency of Middle C (262 Hertz).
let first = 262;
// Create an array of frequencies for the C Major scale based on the frequency of Middle C.
let frequencies = [
first, // Middle C
first * 9/8, // D
first * 5/4, // E
first * 4/3, // F
first * 3/2, // G
first * 5/3, // A
first * 15/8, // B
first * 2 // C (one octave higher)
];
// Initialize an array to hold Oscillator objects.
let oscillators = [];
// Initialize an array to track whether each note is being played.
let noteStates = [false, false, false, false, false, false, false, false];
function setupXylophone() {
// Create an Oscillator for each frequency.
for (let freq of frequencies) {
let osc = new Oscillator(freq);
osc.amp(0);
osc.start();
oscillators.push(osc);
}
}
function drawXylophone() {
// Draw a rectangle for each note.
for (let i = 0; i < 8; i++) {
if (noteStates[i]) {
fill(100, 200, 100); // Highlight color when note is playing.
} else {
fill(200); // Default color when note is not playing.
}
rect(i * 45 + 20, 200, 40, 100); // Position each rectangle with some spacing.
fill(0)
text("(" + (i+1) + ")", i * 47 + 25, 320) //display key number
}
}
function playNote(noteIndex) {
oscillators[noteIndex].amp(1);
noteStates[noteIndex] = true;
}
function stopNote(noteIndex) {
oscillators[noteIndex].amp(0);
noteStates[noteIndex] = false;
}