Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Detect Midi-piano Keyboard Events in the Browser with JavaScript

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);
});
like image 294
Maiya Avatar asked Oct 23 '25 08:10

Maiya


2 Answers

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

like image 56
NVRM Avatar answered Oct 24 '25 21:10

NVRM


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;
  });
}
like image 43
ceving Avatar answered Oct 24 '25 22:10

ceving



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!