-
Notifications
You must be signed in to change notification settings - Fork 2
/
note-player.js
66 lines (52 loc) · 1.74 KB
/
note-player.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
// Play tones and sounds when notes are triggered from a keyboard or MIDI input.
function initNotePlayer({ synth, soundGenerator, oscilloscope }){
const NOTES = [ 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B' ];
const padMapping = {
36: () => soundGenerator.playSound('kick'),
37: () => soundGenerator.playSound('drysnare'),
38: () => soundGenerator.playSound('closedhihat'),
39: () => soundGenerator.playSound('openhihat'),
};
const commandMapping = {
106: () => synth.switchPatch(-1),
107: () => synth.switchPatch(),
};
const activeNotes = {};
function stopNote({ note, channel }) {
const { stop } = activeNotes[note] || {};
if (typeof stop === 'function') stop();
delete activeNotes[note];
}
function playNote({ note, channel, velocity }) {
console.log('playNote', { note, channel, velocity });
if (channel === 10) {
padMapping[note]({ velocity });
} else {
// white and black keys
stopNote({ note, channel });
const octave = Math.floor(note / 12);
const noteIdx = note % 12;
const { oscillator, gainNode } = synth.playNote({ note: NOTES[noteIdx], octave, velocity });
oscilloscope.connect(gainNode);
function stop() {
oscillator.stop();
oscilloscope.disconnect(gainNode);
}
activeNotes[note] = { stop };
}
}
function playParsedMidiMessage({ command, note, channel, velocity }) {
const commandKey = command === 11;
const keyUp = command === 8;
if (commandKey) {
if (velocity > 0) commandMapping[note]();
} else if (keyUp) {
stopNote({ note, channel });
} else {
playNote({ note, channel, velocity });
}
};
return {
playParsedMidiMessage
};
}