-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
midi.ts
56 lines (48 loc) · 1.14 KB
/
midi.ts
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
import {Emitter} from '../Emitter'
import {Memoized, memoizeFunction} from '../memoize'
export type MIDIData = [number, number, number]
/**
* @group Emitters
*/
export class MidiEmitter extends Emitter<MIDIData> {
constructor() {
super()
this.#init()
}
async #init() {
if (!navigator.requestMIDIAccess) {
// eslint-disable-next-line no-console
console.error('Cannot access MIDI devices on this browser')
return
}
const midi = await navigator.requestMIDIAccess()
if (!midi) {
// eslint-disable-next-line no-console
console.error('Cannot access MIDI devices on this browser')
return
}
midi.inputs.forEach(input => {
input.addEventListener('midimessage', evt => {
const value = [...evt.data] as MIDIData
this.emit(value)
})
})
}
/**
* @group Filters
*/
@Memoized()
note(channel: number, note: number): Emitter<number> {
return this.filterMap(([status, _note, velocity]: MIDIData) => {
if (status === 176 + channel && _note === note) {
return velocity
} else {
return undefined
}
}, 0)
}
}
/**
* @group Generators
*/
export const midi = memoizeFunction(() => new MidiEmitter())