xxxxxxxxxx
60
// Boolean variable for melody playing state.
let isPlaying = false;
// Variable for Oscillator.
let osc;
function setup() {
createCanvas(400,400);
// Initialize oscillators and place in oscillators array.
for (let freq of frequencies) {
osc = new Oscillator(freq);
oscillators.push(osc);
}
// Set the text style.
textAlign(CENTER, CENTER);
textSize(30);
}
function draw() {
background(220);
// Display melody name.
text(melody.name, width / 2, 50);
// Display instruction if melody is not playing.
if (isPlaying === false) {
text('Click to play', width / 2, height / 2);
} else {
// Display frequency using for loop looking through oscillator array.
for (let sound of oscillators) {
// Check if the oscillator is playing.
if (sound.started === true) {
// Get the frequency of the note (round to nearest whole number with floor()).
freq = floor(sound.getFreq());
// Display the frequency.
text(`${freq} Hz`, width / 2, height / 2);
}
}
}
}
// Plays the melody when when the mouse is pressed.
function mousePressed() {
// Play melody.
if (isPlaying === false) {
play();
isPlaying = true;
}
}
// Stops the oscillator when the mouse is released.
function mouseReleased() {
osc.stop();
}