-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
65 lines (49 loc) · 1.65 KB
/
index.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
62
63
64
65
var floor = Math.floor;
function clamp(min, max, v) {
if (v < min) return min;
if (v > max) return max;
return v;
}
module.exports = function(audioContext, opts) {
opts = opts || {};
var bufferSize = opts.bufferSize || 4096,
channelCount = opts.channelCount || 2,
bits = clamp(1, Infinity, (opts.bitDepth || 8) | 0),
normFreq = clamp(0, 1, opts.frequency || 1),
step = 2 * Math.pow(0.5, bits),
invStep = 1 / step,
phasor = 0,
last = 0;
var processor = audioContext.createScriptProcessor(bufferSize, channelCount, channelCount);
processor.onaudioprocess = function(evt) {
var ib = evt.inputBuffer,
ob = evt.outputBuffer;
for (var i = 0; i < channelCount; ++i) {
var id = ib.getChannelData(i),
od = ob.getChannelData(i);
for (var s = 0, l = ob.length; s < l; ++s) {
phasor += normFreq;
if (phasor >= 1) {
phasor -= 1;
last = step * floor((id[s] * invStep) + 0.5);
}
od[s] = last;
}
}
}
Object.defineProperty(processor, 'bitDepth', {
get: function() { return bits; },
set: function(v) {
bits = v;
step = 2 * Math.pow(0.5, bits);
invStep = 1 / step;
}
});
Object.defineProperty(processor, 'frequency', {
get: function() { return normFreq; },
set: function(v) {
normFreq = clamp(0, 1, v);
}
});
return processor;
}