-
Notifications
You must be signed in to change notification settings - Fork 2
/
webmidi-reader.js
49 lines (39 loc) · 1.22 KB
/
webmidi-reader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Generic MIDI message reader
function initWebMidiReader() {
// Turns a generic MIDI message into { timeStamp, channel, command, note, velocity }
function parseMidiMessage(midiMessage) {
var data = midiMessage.data
var channel = (data[0] & 0xf) + 1;
var command = data[0] >> 4;
// cf _parseChannelEvent() from https://github.com/djipco/webmidi/blob/master/src/webmidi.js
return {
timeStamp: midiMessage.timeStamp,
channel,
command,
note: data[1],
velocity: data[2]
};
}
function listenToMidiMessages(handler) {
const emit = (message) => setTimeout(() => handler(message), 0);
const onMIDIFailure = () => emit({
error: 'Could not access your MIDI devices.'
});
function onMIDISuccess(midiAccess) {
// attach message handler to all MIDI inputs
for (var input of midiAccess.inputs.values()) {
console.log('Attaching MIDI device:', input.name);
input.onmidimessage = emit;
}
}
if (!navigator.requestMIDIAccess) {
onMIDIFailure();
} else {
navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure);
}
}
return {
parseMidiMessage,
onMidiMessage: listenToMidiMessages,
};
}