-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeep.js
42 lines (37 loc) · 1.47 KB
/
beep.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
class Beep {
/**
*
* @param {AudioContext} audioContext
*/
constructor(audioContext = null) {
this.audioContext = audioContext;
if (audioContext === null) {
this.audioContext = new (AudioContext || webkitAudioContext || window.webkitAudioContext)();
}
}
playNote(frequency, duration) {
const oscillator = this.audioContext.createOscillator();
const volume = this.audioContext.createGain();
duration = Math.max(duration, 0.03);
/*
const compressor = this.audioContext.createDynamicsCompressor();
oscillator.frequency.value = frequency;
oscillator.type = "sine";
volume.gain.value = 0.1;
oscillator.connect(volume).connect(compressor).connect(this.audioContext.destination);
// Ramp up
volume.gain.exponentialRampToValueAtTime(volume.gain.value, this.audioContext.currentTime+duration);
// Ramp down
volume.gain.exponentialRampToValueAtTime(0.0001, this.audioContext.currentTime+decay);
oscillator.start(this.audioContext.currentTime);
oscillator.stop(this.audioContext.currentTime+decay+duration);
*/
oscillator.frequency.value = frequency;
volume.gain.value = 0.01;
volume.gain.exponentialRampToValueAtTime(volume.gain.value, this.audioContext.currentTime + duration);
volume.gain.exponentialRampToValueAtTime(0.0001, this.audioContext.currentTime + 0.3);
oscillator.connect(volume).connect(this.audioContext.destination);
oscillator.start();
oscillator.stop(this.audioContext.currentTime + duration + 0.01);
}
}