xxxxxxxxxx
62
/*
Play midi notes using WebMIDI.js
*/
let midiVal, midiVelocity, freq, osc, env;
WebMidi.enable(function (err) {
//check if WebMidi.js is enabled
if (err) {
console.log("WebMidi could not be enabled.", err);
} else {
console.log("WebMidi enabled!");
}
// name our visible MIDI input and output ports
console.log("Inputs Ports: ");
for (i = 0; i < WebMidi.inputs.length; i++) {
console.log(i + ": " + WebMidi.inputs[i].name);
}
// choose an input port (0 means use the first device we see)
inputSoftware = WebMidi.inputs[0];
// listen to all incoming "note on" input events
inputSoftware.addListener('noteon', "all",
function (e) {
// Play the note recieved
startSound(e.note.number, e.velocity);
}
);
// listen for noteoff events (not used)
inputSoftware.addListener('noteoff', "all", function (e) {} );
});
function setup() {
let cnv = createCanvas(640, 480);
osc = new p5.TriOsc();
env = new p5.Envelope();
}
function draw() {
background(220);
text('Note info;', 10, 20);
if (midiVal) {
text('MIDI: ' + midiVal, 10, 40);
text('Freq: ' + freq, 10, 60);
circle((midiVal * 5) ,(midiVelocity * 3.8), 20);
}
}
function startSound(noteVal, velocityVal) {
osc.start();
midiVal = noteVal;
midiVelocity = velocityVal;
freq = midiToFreq(noteVal);
env.setADSR(0.001, velocityVal);
osc.freq(freq);
env.ramp(osc, 0, 1.0, 0);
}