Skip to content

Instantly share code, notes, and snippets.

@softpunch
Last active July 3, 2017 00:11
Show Gist options
  • Save softpunch/7c90928cd9593b8e217e32962c7e3d2a to your computer and use it in GitHub Desktop.
Save softpunch/7c90928cd9593b8e217e32962c7e3d2a to your computer and use it in GitHub Desktop.
WebMIDI basic initialization (output only)
//
// Chrome only; no iOS
//
// Initialize WebMidi; create dropdown selector for output port
//
// HTML component:
// <label for="outputSelector">select midi output</label><br>
// <select id="outputSelector" onchange="updatePort()">
// <option value="null" selected>[none]</option>
// </select>
//
// access output selector
var outputSelector = document.querySelector('#outputSelector');
// empty var to hold "midiAccess"
var midi;
// empty var to hold selected MIDI output port ID
var mPort;
// initialize WebMIDI
function onMIDISuccess( midiAccess ) {
midi = midiAccess;
midi.outputs.forEach(
function(port, key) {
var portName = port.name;
var portID = port.id;
var option = document.createElement("option");
option.setAttribute("value", portID);
var textNode = document.createTextNode(portName);
option.appendChild(textNode);
outputSelector.appendChild(option);
});
}
navigator.requestMIDIAccess().then(onMIDISuccess);
// define output port upon selection
function updatePort() {
var i = outputSelector.selectedIndex;
mPort = outputSelector.options[i].value;
}
// define "now"
// if using web audio for timing:
// var now = audioContext.currentTime;
// if not using web audio:
var now = window.performance.now();
// midi -- single note output function
function sendMidiNote( note, vel, dur ) {
var noteOn = 0x90; // midi channel 1
var midiNoteBegin = [noteOn, note, vel];
var midiNoteEnd = [noteOn, note, 0];
var output = midi.outputs.get(mPort);
output.send(midiNoteBegin);
output.send(midiNoteEnd, now + dur);
}
// example usage:
// send Middle C (midi note #60)
// at maximum velocity (velocity range is 0-127)
// for one second (durations are in ms)
// on midi channel #1 (function defaults to channel 1)
//
// sendMidiNote(60, 127, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment