-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
82 lines (66 loc) · 2.59 KB
/
script.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
const audioContext = new AudioContext();
// create an element to show the note being played
// const notePlaying = document.createElement("div");
// notePlaying.className = "note-playing";
// document.body.appendChild(notePlaying);
// select where to place key/note output under the piano
const notePlaying = document.querySelector(".note-playing");
const NOTE_DETAILS = [
{ note: "C", key: "Z", frequency: 261.626, active: false },
{ note: "Db", key: "S", frequency: 277.183, active: false },
{ note: "D", key: "X", frequency: 293.665, active: false },
{ note: "Eb", key: "D", frequency: 311.127, active: false },
{ note: "E", key: "C", frequency: 329.628, active: false },
{ note: "F", key: "V", frequency: 349.228, active: false },
{ note: "Gb", key: "G", frequency: 369.994, active: false },
{ note: "G", key: "B", frequency: 391.995, active: false },
{ note: "Ab", key: "H", frequency: 415.305, active: false },
{ note: "A", key: "N", frequency: 440, active: false },
{ note: "Bb", key: "J", frequency: 466.164, active: false },
{ note: "B", key: "M", frequency: 493.883, active: false },
];
document.addEventListener("keydown", (e) => {
if (e.repeat) return;
const keyboardKey = e.code;
const noteDetail = getNoteDetails(keyboardKey);
// display what key/note combo is playing
notePlaying.innerHTML = `you pressed ${keyboardKey}, which plays the note of ${noteDetail.note}`;
if (noteDetail == null) return;
noteDetail.active = true;
playNotes();
});
document.addEventListener("keyup", (e) => {
const keyboardKey = e.code;
const noteDetail = getNoteDetails(keyboardKey);
if (noteDetail == null) return;
noteDetail.active = false;
playNotes();
});
function getNoteDetails(keyboardKey) {
return NOTE_DETAILS.find((n) => `Key${n.key}` === keyboardKey);
}
function playNotes() {
NOTE_DETAILS.forEach((n) => {
const keyElement = document.querySelector(`[data-note="${n.note}"]`);
keyElement.classList.toggle("active", n.active);
if (n.oscillator != null) {
n.oscillator.stop();
n.oscillator.disconnect();
}
});
const activeNotes = NOTE_DETAILS.filter((n) => n.active);
const gain = 1 / activeNotes.length;
activeNotes.forEach((n) => {
startNote(n, gain);
});
}
function startNote(noteDetail, gain) {
const gainNode = audioContext.createGain();
gainNode.gain.value = gain;
const oscillator = audioContext.createOscillator();
oscillator.frequency.value = noteDetail.frequency;
oscillator.type = "sine";
oscillator.connect(gainNode).connect(audioContext.destination);
oscillator.start();
noteDetail.oscillator = oscillator;
}