Visualizzazione di input MIDI
Usando le Web MIDI API (ben supportate da Google Chrome) è possibile leggere direttamente i dati provenienti da uno strumento MIDI collegato al computer:
// height=300 lines=68
let noteVisible = false; // visibilità della nota
let noteHue = 0; // tonalità cromatica della nota
let noteDiamPerc = 0.0; // dimensione nota in "percentuale", dove 0.0 è sempre 0 e 1.0 arriva a "noteDiamMax"
let noteDiamMax = 300; // diametro massimo del cerchio/nota
function setup() {
createCanvas( 670, 300 );
colorMode( HSL, 360,100,100 );
}
function draw() {
background(100);
// disegna nota, se visibile
if (noteVisible) {
noStroke();
fill( noteHue, 100, 50 );
circle( width/2,height/2, noteDiamPerc*noteDiamMax );
}
}
function noteOn( note, velocity ) { // quando inizia una nota...
noteVisible = true;
noteHue = map( note, 24,95, 0,360 );
noteDiamPerc = map( velocity, 0,127, 0,0.5 );
}
function noteOff( note ) { // quando finisce una nota...
noteVisible = false;
}
function midiInput( data1, data2, data3 ) { // quando viene azionato un altro controllo...
print( "midiInput: "+data1+", "+data2+", "+data3 );
}
////////////////////////////////////////////////////////////////////////////////
// GESTIONE INPUT MIDI
navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure);
function onMIDIFailure() {
print('Could not access your MIDI devices.');
}
function onMIDISuccess(midiAccess) {
for (let input of midiAccess.inputs.values()) {
input.onmidimessage = getMIDIMessage;
}
}
function getMIDIMessage(message) {
let command = message.data[0];
let note = message.data[1];
let velocity = (message.data.length > 2) ? message.data[2] : 0;
switch (command) {
case 144: // inizio nota
noteOn(note, velocity);
break;
case 128: // fine nota
noteOff(note, velocity);
break;
default: // altri controlli
midiInput(message.data[0], message.data[1], (message.data.length > 2) ? message.data[2] : 0);
break;
}
}
Per far funzionare lo sketch è ovviamente necessario collegare al computer una periferica MIDI, ad esempio una tastiera o un controller, e "suonarla".