-
Notifications
You must be signed in to change notification settings - Fork 0
/
midi.js
53 lines (44 loc) · 1.3 KB
/
midi.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
50
51
52
53
class Midi {
latest = {};
listeners = {};
inputs = [];
outputs = [];
audioIn = null;
setup = async () => {
await navigator
.requestMIDIAccess()
.then(this.onAccessAllowed)
.catch(this.onAccessRefused);
};
onAccessAllowed = async controller => {
this.inputs = this.call("inputs_changed", Array.from(controller.inputs));
this.outputs = this.call("outputs_changed", Array.from(controller.outputs));
this.selectIn(localStorage.getItem("audioin"));
};
selectIn = id => {
const audioIn = (this.inputs || []).find(([inputId]) => inputId === id);
if (audioIn && audioIn[1] && audioIn[1] instanceof MIDIInput) {
localStorage.setItem("audioin", id);
this.audioIn = this.call("audioin_changed", audioIn);
}
};
on = (event, callback) => {
this.listeners[event] = (this.listeners[event] || []).concat(callback);
if (event in this.latest) callback(this.latest[event]);
};
off = event => {
delete this.listeners[event];
};
call = (event, value) => {
this.latest[event] = value;
if (event in this.listeners) {
if (Array.isArray(this.listeners[event])) {
this.listeners[event].forEach(callback => callback(value));
}
}
return value;
};
}
const midi = new Midi();
midi.setup();
export default midi;