// Store last received values (for display only)
let lastNote = "No note yet";
let lastCC = "No controller yet";
let midiInputs = [];
function setup() {
createCanvas(windowWidth, windowHeight);
textSize(24);
textAlign(LEFT, TOP);
fill(255);
// Request MIDI access
if (navigator.requestMIDIAccess) {
navigator.requestMIDIAccess()
.then(onMIDISuccess, onMIDIFailure);
}
}
function draw() {
background(0);
// Display latest note and controller info
text("Last NOTE: " + lastNote, 20, 20);
text("Last CONTROL CHANGE: " + lastCC, 20, 60);
text("Connected MIDI inputs: " + midiInputs.length, 20, 120);
}
// ------------------------------------------------------------
// MIDI SETUP
// ------------------------------------------------------------
function onMIDISuccess(midi) {
// Register all MIDI inputs
for (let input of midi.inputs.values()) {
midiInputs.push(input);
input.onmidimessage = handleMIDIMessage;
}
}
function onMIDIFailure(err) {
console.error("Could not access MIDI devices.", err);
}
// ------------------------------------------------------------
// MIDI MESSAGE HANDLING
// ------------------------------------------------------------
function handleMIDIMessage(message) {
let [status, data1, data2] = message.data;
let command = status & 0xf0; // note on, note off, cc etc.
// NOTE ON (and velocity > 0)
if (command === 0x90 && data2 > 0) {
lastNote = `Note ${data1} | velocity ${data2}`;
}
// NOTE OFF
else if (command === 0x80 || (command === 0x90 && data2 === 0)) {
lastNote = `Note ${data1} released`;
}
// CONTROL CHANGE
else if (command === 0xB0) {
lastCC = `CC ${data1} | value ${data2}`;
}
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}