/
sound.js
57 lines (48 loc) · 1.11 KB
/
sound.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
(function () {
const ctx = new (window.AudioContext || window.webkitAudioContext);
var started = false;
var muted = false;
const oscillator = ctx.createOscillator();
var gainNode = ctx.createGain();
oscillator.connect(gainNode);
gainNode.connect(ctx.destination);
function sound(freq, ms) {
if (muted) return new Promise(()=>{});
if (!started) oscillator.start();
started = true;
oscillator.type = 'sine';
oscillator.frequency.value = freq;
gainNode.gain.value = 1;
return new Promise((resolve) => {
setTimeout(() => {
gainNode.gain.value = 0.4;
setTimeout(() => {
gainNode.gain.value = 0.0;
}, 200);
resolve();
}, ms);
});
}
let t0 = +new Date;
let index = 0;
function next() {
const note = data[index++];
if (!note) {
return
};
sound(note[0], note[1]).then(next);
}
function melody(m) {
data = m;
index = 0;
next();
}
window.toggleSound = () => {
muted = !muted;
if (muted) {
gainNode.gain.value = 0.0;
}
};
window.sound = sound;
window.melody = melody;
})();