Reputation: 980
I would like to plug a midi piano keyboard into my computer's USB port, and respond to the key events by displaying something in the browser.
Does anyone know of a way that will allow JavaScript to interact with USB midi keyboard events in the front-end/browser?
Something like:
script.js file linked to index.html:
$(document).on('midi-key-press', function(event) {
alert('the key that you pressed was ' + event.whichKey);
});
Upvotes: 4
Views: 2401
Reputation: 23863
Nowadays you can use the Web MIDI API:
function onMIDIMessage(event) {
let str = `MIDI message received at timestamp ${event.timeStamp}[${event.data.length} bytes]: `;
for (const character of event.data) {
str += `0x${character.toString(16)} `;
}
console.log(str);
}
function startLoggingMIDIInput(midiAccess) {
midiAccess.inputs.forEach((entry) => {
entry.onmidimessage = onMIDIMessage;
});
}
Upvotes: 1
Reputation: 13156
Webkits browsers have a native api.
Best is to check the specs in details: https://webaudio.github.io/web-midi-api/
About Firefox, this was asked since long time. It seems that support is coming.
https://bugzilla.mozilla.org/show_bug.cgi?id=836897
I use to made a little workaround with the web midi api. It detects any midi rotary knobs on any channel and will change the background color of the page. Based on the script samples provided by the specs.
Hopefully you will find something interesting.
https://github.com/webdev23/midiKnobControl
To be fair, it is a very powerful but hard to handle api.
This need a good knowledge of the midi protocol, know well your midi devices, and be up to date with javascript. It is also important to know how works the web audio api: https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API
edit: Mozilla is on it: https://github.com/mozilla/standards-positions/issues/58
Upvotes: 5