-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
58 lines (49 loc) · 1.41 KB
/
app.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
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const keyboard = {
a: 'C3',
s: 'D3',
d: 'E3',
f: 'F3',
j: 'G3',
k: 'A3',
l: 'B3',
';': 'C4',
};
const FREQUENCY_FOR_KEY = {
C3: 130.8128,
D3: 146.8324,
E3: 164.8138,
F3: 174.6141,
G3: 195.9977,
A3: 220.0,
B3: 246.9417,
C4: 261.6256,
};
let state = {
volume: 0.5,
};
const makeNoteSound = (f) => {
const oscillator = audioCtx.createOscillator()
, gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
oscillator.type = 'square';
oscillator.frequency.value = f;
gainNode.connect(audioCtx.destination);
gainNode.gain.value = state.volume;
gainNode.gain.exponentialRampToValueAtTime(0.00001, audioCtx.currentTime + 2);
oscillator.start();
};
window.addEventListener('keydown', (e) => {
if (keyboard[e.key] === undefined) return;
document.querySelector('#' + keyboard[e.key]).classList.add('clicked');
makeNoteSound(FREQUENCY_FOR_KEY[keyboard[e.key]]);
});
window.addEventListener('keyup', (e) => {
if (keyboard[e.key] === undefined) return;
document.querySelector('#' + keyboard[e.key]).classList.remove('clicked');
});
const volumeController = document.querySelector('.volume-controller__input');
volumeController.addEventListener('input', e => {
const {target} = e;
state.volume = parseFloat(target.value);
});