-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinstruments.js
60 lines (59 loc) · 1.78 KB
/
instruments.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
class Instrument {
constructor (target, type) {
this.type = type
this.context = target.context ? target.context : target
this.target = target.destination ? target.destination : target
}
play (pitch, time) {
if (this.note) this.stop(time)
this.note = new OscillatorNote(this.target,
{ attack: 0.01, sustain: 0.4, triggerTime: time },
[{ frequency: midiToFrequency(pitch), type: this.type }])
}
release () {
if (this.note) this.note.releaseNote(time)
this.note = undefined
}
stop (time) {
if (this.note) this.note.stopNote(time)
this.note = undefined
}
}
class NoiseInstrument {
constructor (target) {
this.target = target
this.context = target.context ? target.context : target
this.buffer = this.context.createBuffer(1,
this.context.sampleRate * 8, this.context.sampleRate)
let data = this.buffer.getChannelData(0)
for (let i = 0; i < data.length; i++) {
data[i] = Math.random() * 0.28 - 0.14
}
this.filter = new BiquadFilterNode(this.context, { type: 'bandpass' })
this.waveshaper = new WaveShaperNode(this.context, {
curve: Float32Array.from([1, 0.8, 0.3, 0, -0.3, -0.8, -1])
})
this.compressor = new DynamicsCompressorNode(this.context, {
attack: 0.15,
knee: 0,
ratio: 20,
release: 0.1,
threshold: -40
})
this.filter.connect(this.compressor)
.connect(this.waveshaper)
.connect(this.target)
}
play (pitch) {
if (this.source) this.source.stop()
this.filter.frequency.value = midiToFrequency(pitch)
this.source = this.context.createBufferSource()
this.source.buffer = this.buffer
this.source.connect(this.filter)
this.source.start()
}
stop () {
if (this.source) this.source.stop()
this.source = undefined
}
}