-
Notifications
You must be signed in to change notification settings - Fork 3
/
key.js
61 lines (42 loc) · 1.22 KB
/
key.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
// A single key, that synthetize its own sound and keep track of its own state
const Key = function(){
this.isDown = false;
this.ratio = 2.4;
this.frequency = 1;
this.switch = context.createGain();
this.output = context.createGain();
this.harmonics = [];
Organ.harmonicRatios.forEach(ratio => {
const oscillator = context.createOscillator();
oscillator.type = "sine";
oscillator.start();
const gain = context.createGain();
oscillator.connect(gain);
gain.connect(this.switch);
this.harmonics.push({ratio, oscillator, gain});
});
this.switch.connect(this.output);
this.updateHarmonicLevels();
this.keyDown();
this.keyUp();
return this;
}
Key.prototype.updateHarmonicLevels = function() {
Organ.harmonicLevels.forEach((level, index) => this.harmonics[index].gain.gain.value = level);
}
Key.prototype.setFrequency = function(frequency) {
this.frequency = frequency;
this.harmonics.forEach(harmonic => {
harmonic.oscillator.frequency.value = frequency * harmonic.ratio;
});
}
Key.prototype.keyDown = function(){
if(this.isDown) return;
this.isDown = true;
this.switch.gain.value = 1.0;
}
Key.prototype.keyUp = function(){
if(!this.isDown) return;
this.isDown = false;
this.switch.gain.value = 0.0;
}