forked from adelespinasse/reverbGen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverbgen.js
216 lines (187 loc) · 7.88 KB
/
reverbgen.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// Copyright 2014 Alan deLespinasse, jipodine
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
"use strict";
var reverbGen = {};
(function() {
/** Generates a reverb impulse response.
@param {!Object} params TODO: Document the properties.
@param {!function(!AudioBuffer)} callback Function to call when
the impulse response has been generated. The impulse response
is passed to this function as its parameter. May be called
immediately within the current execution context, or later. */
reverbGen.generateReverb = function(params, callback) {
var sampleRate = params.sampleRate || 0;
var numChannels = params.numChannels || 2;
var fadeInTime = params.fadeInTime || 0;
var decayThreshold = params.decayThreshold || -60;
var decayTime = params.decayTime || 5;
var fadeInSampleFrames = Math.round(fadeInTime * sampleRate);
var decaySampleFrames = Math.round(decayTime * sampleRate);
var numSampleFrames = fadeInSampleFrames + decaySampleFrames;
var decayBase = Math.pow(dBToPower(decayThreshold), 1 / (numSampleFrames - 1));
var context = new OfflineAudioContext(numChannels, numSampleFrames, sampleRate);
if(context === null) {
callback(null);
return;
}
var reverbIR = context.createBuffer(numChannels, numSampleFrames, sampleRate);
var fadeInFactor = 1 / (fadeInSampleFrames - 1);
for (var i = 0; i < numChannels; i++) {
var chan = reverbIR.getChannelData(i);
for (var j = 0; j < numSampleFrames; j++) {
chan[j] = randomSample() * Math.pow(decayBase, j);
}
for (var j = 0; j < fadeInSampleFrames; j++) {
chan[j] *= j * fadeInFactor;
}
}
applyGradualLowpass(reverbIR, params.lpFreqStart || 0, params.lpFreqEnd || 0,
params.fadeInTime + params.decayTime, callback);
};
/** Creates a canvas element showing a graph of the given data.
@param {!Float32Array} data An array of numbers, or a Float32Array.
@param {number} width Width in pixels of the canvas.
@param {number} height Height in pixels of the canvas.
@param {number} min Minimum value of data for the graph (lower edge).
@param {number} max Maximum value of data in the graph (upper edge).
@return {!CanvasElement} The generated canvas element. */
reverbGen.generateGraph = function(data, width, height, min, max) {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var gc = canvas.getContext('2d');
gc.fillStyle = '#000';
gc.fillRect(0, 0, canvas.width, canvas.height);
gc.fillStyle = '#fff';
var xscale = width / data.length;
var yscale = height / (max - min);
for (var i = 0; i < data.length; i++) {
gc.fillRect(i * xscale, height - (data[i] - min) * yscale, 1, 1);
}
return canvas;
}
/** Saves an AudioBuffer as a 16-bit WAV file on the client's host
file system. Normalizes it to peak at +-32767, and optionally
truncates it if there's a lot of "silence" at the end.
@param {!AudioBuffer} buffer The buffer to save.
@param {string} name Name of file to create. */
reverbGen.saveWavFile = function(buffer, name) {
var bitsPerSample = 16;
var bytesPerSample = 2;
var sampleRate = buffer.sampleRate;
var numChannels = buffer.numberOfChannels;
var channels = getAllChannelData(buffer);
var numSampleFrames = channels[0].length;
var scale = 32767;
// Find normalization constant.
var max = 0;
for (var i = 0; i < numChannels; i++) {
for (var j = 0; j < numSampleFrames; j++) {
max = Math.max(max, Math.abs(channels[i][j]));
}
}
if (max) {
scale = 32767 / max;
}
var sampleDataBytes = bytesPerSample * numChannels * numSampleFrames;
var fileBytes = sampleDataBytes + 44;
var arrayBuffer = new ArrayBuffer(fileBytes);
var dataView = new DataView(arrayBuffer);
dataView.setUint32(0, 1179011410, true); // "RIFF"
dataView.setUint32(4, fileBytes - 8, true); // file length
dataView.setUint32(8, 1163280727, true); // "WAVE"
dataView.setUint32(12, 544501094, true); // "fmt "
dataView.setUint32(16, 16, true) // fmt chunk length
dataView.setUint16(20, 1, true); // PCM format
dataView.setUint16(22, numChannels, true); // NumChannels
dataView.setUint32(24, sampleRate, true); // SampleRate
var bytesPerSampleFrame = numChannels * bytesPerSample;
dataView.setUint32(28, sampleRate * bytesPerSampleFrame, true); // ByteRate
dataView.setUint16(32, bytesPerSampleFrame, true); // BlockAlign
dataView.setUint16(34, bitsPerSample, true); // BitsPerSample
dataView.setUint32(36, 1635017060, true); // "data"
dataView.setUint32(40, sampleDataBytes, true);
for (var j = 0; j < numSampleFrames; j++) {
for (var i = 0; i < numChannels; i++) {
dataView.setInt16(44 + j * bytesPerSampleFrame + i * bytesPerSample,
Math.round(scale * channels[i][j]), true);
}
}
var blob = new Blob([arrayBuffer], {'type': 'audio/wav'});
var url = window.URL.createObjectURL(blob);
var linkEl = document.createElement('a');
linkEl.href = url;
linkEl.download = name;
linkEl.style.display = 'none';
document.body.appendChild(linkEl);
linkEl.click();
};
/** Applies a constantly changing lowpass filter to the given sound.
@private
@param {!AudioBuffer} input
@param {number} lpFreqStart
@param {number} lpFreqEnd
@param {number} lpFreqEndAt
@param {!function(!AudioBuffer)} callback May be called
immediately within the current execution context, or later.*/
var applyGradualLowpass = function(input, lpFreqStart, lpFreqEnd, lpFreqEndAt, callback) {
if (lpFreqStart == 0) {
callback(input);
return;
}
var channelData = getAllChannelData(input);
var context = new OfflineAudioContext(input.numberOfChannels, channelData[0].length, input.sampleRate);
if(context === null) {
callback(null);
return;
}
var player = context.createBufferSource();
player.buffer = input;
var filter = context.createBiquadFilter();
lpFreqStart = Math.min(lpFreqStart, input.sampleRate / 2);
lpFreqEnd = Math.min(lpFreqEnd, input.sampleRate / 2);
filter.type = "lowpass";
filter.Q.value = 0.0001;
filter.frequency.setValueAtTime(lpFreqStart, 0);
filter.frequency.exponentialRampToValueAtTime(lpFreqEnd, lpFreqEndAt);
player.connect(filter);
filter.connect(context.destination);
player.start();
context.oncomplete = function(event) {
callback(event.renderedBuffer);
};
context.startRendering();
// window.filterNode = filter;
};
/** @private
@param {!AudioBuffer} buffer
@return {!Array.<!Float32Array>} An array containing the Float32Array of each channel's samples. */
var getAllChannelData = function(buffer) {
var channels = [];
for (var i = 0; i < buffer.numberOfChannels; i++) {
channels[i] = buffer.getChannelData(i);
}
return channels;
};
/** @private
@return {number} A random number from -1 to 1. */
var randomSample = function() {
return Math.random() * 2 - 1;
};
/** @private
@return {number} An exponential gain value (1e-6 for -60dB*/
var dBToPower = function(dBValue) {
return Math.pow(10, dBValue / 10);
};
}());