-
-
Save sc0ttj/32384cd577040f63ab77a081fff1bc97 to your computer and use it in GitHub Desktop.
Web MIDI API with maps (select ports)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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