-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (80 loc) · 2.19 KB
/
index.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import Emitter from 'events/'
export default (input, output) => (
new GenericMIDIController(input, output)
)
class GenericMIDIController extends Emitter {
constructor (inputs, outputs) {
super()
this.input = null
this.inputs = {}
this.output = null
this.outputs = {}
this.outputBuffer = []
outputs = outputs || {}
inputs = inputs || {}
this.midiMessage = this._midiMessage(inputs)
Object.keys(outputs).forEach(group => {
var data = this.outputs[group] = {}
outputs[group].forEach((fn, id) => {
var value = 0
Object.defineProperty(data, id, {
get: _ => value,
set: _value => {
fn(value = _value, data => this.send(data))
this.emit('output', group, id, value)
}
})
})
})
}
setInput (input) {
if (this.input) {
this.input.removeEventListener('midimessage', this.midiMessage, false)
}
this.inputReady = false
this.input = input
this.input.open().then(_ => this.inputReady = true)
this.input.addEventListener('midimessage', this.midiMessage, false)
}
setOutput (output) {
this.outputReady = false
this.output = output
this.output.open().then(_ => {
this.outputBuffer.forEach(msg => this.output.send(msg))
this.outputBuffer = []
this.outputReady = true
})
}
send (data) {
if (this.outputReady) {
return this.output.send(data)
} else {
return this.outputBuffer.push(data)
}
}
_midiMessage (inputs) {
const keys = Object.keys(inputs)
for (var i = 0; i < keys.length; i++) {
var rows = inputs[keys[i]]
var data = this.inputs[keys[i]] = []
for (var j = 0; j < rows.length; j++) {
data[j] = 0
}
}
return event => {
var message = event.data
for (var i = 0; i < keys.length; i++) {
var key = keys[i]
var grp = inputs[key]
for (var j = 0; j < grp.length; j++) {
var val = grp[j](message)
if (typeof val === 'number') {
this.inputs[key][j] = val
this.emit('input', key, j, val)
}
}
}
this.emit('message', event.data)
}
}
}