Skip to content

Instantly share code, notes, and snippets.

@jussi-kalliokoski
Last active December 19, 2015 13:09
Show Gist options
  • Save jussi-kalliokoski/5960415 to your computer and use it in GitHub Desktop.
Save jussi-kalliokoski/5960415 to your computer and use it in GitHub Desktop.
Web MIDI API with maps
var select = document.createElement('select');
var selectedPort = null;
var onMessage = function (event) {
// TODO: Use the message
};
var selectPort = function (id) {
var newPort = midiAccess.inputs.get(id);
if ( !newPort ) {
throw new Error("Invalid port id");
}
if ( selectedPort ) {
selectedPort.removeEventListener('midimessage', onMessage);
}
// save ID for remembering the port
localStorage.setItem('port-id', id);
selectedPort = newPort;
selectedPort.addEventListener('midimessage', onMessage);
};
try {
// attempt to select the port that was in use last time
selectPort(localStorage.getItem('port-id'));
} catch ( error ) {
// ignore
}
for ( let [ id, port ] of midiAccess.inputs.items() ) {
let option = document.createElement('option');
option.value = id;
option.innerHTML = port.manufacturer + ' ' + port.name;
options.selected = !!selectedPort && selectedPort.id === id;
select.appendChild(option);
}
select.onchange = function () {
selectPort(select.value);
};
// show the selection
document.body.appendChild(select);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment