forked from acidsound/band4all
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplaypiano.js
38 lines (33 loc) · 1.08 KB
/
playpiano.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
const midi2Freq = (midi) => Math.pow(2, (midi - 69) / 12) * 440;
const playPiano = function (context, vel, freq) {
const c = context.currentTime;
const osc = context.createOscillator();
osc.type = "square";
osc.frequency.value = freq;
const gain = context.createGain();
osc.connect(gain);
gain.connect(context.destination);
osc.start(c);
gain.gain.setValueAtTime(0, c);
gain.gain.linearRampToValueAtTime(vel, c + 0.01);
gain.gain.linearRampToValueAtTime(vel * 0.3, c + 0.2);
gain.gain.linearRampToValueAtTime(0, c + 0.4);
osc.stop(context.currentTime + 1);
};
playKey = function (vel, key, isLocal = true) {
let elem = document.querySelector(`[data-note='${key}']`);
if (vel > 0) {
if (!isLocal) {
elem && elem.classList.add("active--network");
} else {
elem && elem.classList.add("active");
}
playPiano(context, vel, midi2Freq(+key));
} else {
elem && elem.classList.remove("active");
elem && elem.classList.remove("active--network");
}
if (isLocal) {
broadCast({ destination: room, patch: "piano", vel, key });
}
};