xxxxxxxxxx
73
let osc; // Oscillator for generating sound
let midiToFreqMap; // Store MIDI-to-frequency mappings
let playing = false;
function setup() {
createCanvas(400, 200);
textAlign(CENTER, CENTER);
textSize(16);
// Initialize an oscillator
osc = new p5.Oscillator('sine');
osc.start();
osc.amp(0); // Start silent
// Create a mapping for MIDI notes to frequencies
midiToFreqMap = {};
for (let midi = 21; midi <= 108; midi++) { // Piano range (A0 to C8)
midiToFreqMap[midi] = midiToFreq(midi);
}
text("Press keys A-L for piano notes!", width / 2, height / 2);
}
function draw() {
background(220);
}
// Function to play MIDI note when a key is pressed
function keyPressed() {
let midiNote = getMidiFromKey(key); // Map the key to a MIDI note
if (midiNote) {
let freq = midiToFreqMap[midiNote]; // Get the frequency for the MIDI note
if (freq) {
playNote(freq); // Play the note
}
}
}
function keyReleased() {
stopNote(); // Stop the note when key is released
}
// Map specific keys to MIDI notes (A-L corresponds to white keys)
function getMidiFromKey(key) {
const midiKeys = {
'A': 60, // Middle C
'S': 62, // D
'D': 64, // E
'F': 65, // F
'G': 67, // G
'H': 69, // A
'J': 71, // B
'K': 72, // High C
'L': 74 // D
};
return midiKeys[key.toUpperCase()] || null;
}
// Function to play a note
function playNote(freq) {
osc.freq(freq); // Set oscillator frequency
osc.amp(0.5, 0.1); // Smooth fade-in
playing = true;
}
// Function to stop the note
function stopNote() {
osc.amp(0, 0.1); // Smooth fade-out
playing = false;
}