This repository was archived by the owner on Oct 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathapp.js
332 lines (272 loc) · 9.69 KB
/
app.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
const heading = document.querySelector("h1");
heading.textContent = "CLICK HERE TO START";
document.body.addEventListener("click", init);
function init() {
heading.textContent = "Voice-change-O-matic";
document.body.removeEventListener("click", init);
// Older browsers might not implement mediaDevices at all, so we set an empty object first
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
// Some browsers partially implement mediaDevices. We can't assign an object
// with getUserMedia as it would overwrite existing properties.
// Add the getUserMedia property if it's missing.
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function (constraints) {
// First get ahold of the legacy getUserMedia, if present
const getUserMedia =
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
// Some browsers just don't implement it - return a rejected promise with an error
// to keep a consistent interface
if (!getUserMedia) {
return Promise.reject(
new Error("getUserMedia is not implemented in this browser")
);
}
// Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
return new Promise(function (resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
};
}
// Set up forked web audio context, for multiple browsers
// window. is needed otherwise Safari explodes
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const voiceSelect = document.getElementById("voice");
let source;
let stream;
// Grab the mute button to use below
const mute = document.querySelector(".mute");
// Set up the different audio nodes we will use for the app
const analyser = audioCtx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
analyser.smoothingTimeConstant = 0.85;
const distortion = audioCtx.createWaveShaper();
const gainNode = audioCtx.createGain();
const biquadFilter = audioCtx.createBiquadFilter();
const convolver = audioCtx.createConvolver();
const echoDelay = createEchoDelayEffect(audioCtx);
// Distortion curve for the waveshaper, thanks to Kevin Ennis
// http://stackoverflow.com/questions/22312841/waveshaper-node-in-webaudio-how-to-emulate-distortion
function makeDistortionCurve(amount) {
let k = typeof amount === "number" ? amount : 50,
n_samples = 44100,
curve = new Float32Array(n_samples),
deg = Math.PI / 180,
i = 0,
x;
for (; i < n_samples; ++i) {
x = (i * 2) / n_samples - 1;
curve[i] = ((3 + k) * x * 20 * deg) / (Math.PI + k * Math.abs(x));
}
return curve;
}
// Grab audio track via XHR for convolver node
let soundSource;
ajaxRequest = new XMLHttpRequest();
ajaxRequest.open(
"GET",
"https://mdn.github.io/voice-change-o-matic/audio/concert-crowd.ogg",
true
);
ajaxRequest.responseType = "arraybuffer";
ajaxRequest.onload = function () {
const audioData = ajaxRequest.response;
audioCtx.decodeAudioData(
audioData,
function (buffer) {
soundSource = audioCtx.createBufferSource();
convolver.buffer = buffer;
},
function (e) {
console.log("Error with decoding audio data" + e.err);
}
);
};
ajaxRequest.send();
// Set up canvas context for visualizer
const canvas = document.querySelector(".visualizer");
const canvasCtx = canvas.getContext("2d");
const intendedWidth = document.querySelector(".wrapper").clientWidth;
canvas.setAttribute("width", intendedWidth);
const visualSelect = document.getElementById("visual");
let drawVisual;
// Main block for doing the audio recording
if (navigator.mediaDevices.getUserMedia) {
console.log("getUserMedia supported.");
const constraints = { audio: true };
navigator.mediaDevices
.getUserMedia(constraints)
.then(function (stream) {
source = audioCtx.createMediaStreamSource(stream);
source.connect(distortion);
distortion.connect(biquadFilter);
biquadFilter.connect(gainNode);
convolver.connect(gainNode);
echoDelay.placeBetween(gainNode, analyser);
analyser.connect(audioCtx.destination);
visualize();
voiceChange();
})
.catch(function (err) {
console.log("The following gUM error occured: " + err);
});
} else {
console.log("getUserMedia not supported on your browser!");
}
function visualize() {
WIDTH = canvas.width;
HEIGHT = canvas.height;
const visualSetting = visualSelect.value;
console.log(visualSetting);
if (visualSetting === "sinewave") {
analyser.fftSize = 2048;
const bufferLength = analyser.fftSize;
console.log(bufferLength);
// We can use Float32Array instead of Uint8Array if we want higher precision
// const dataArray = new Float32Array(bufferLength);
const dataArray = new Uint8Array(bufferLength);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
const draw = function () {
drawVisual = requestAnimationFrame(draw);
analyser.getByteTimeDomainData(dataArray);
canvasCtx.fillStyle = "rgb(200, 200, 200)";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = "rgb(0, 0, 0)";
canvasCtx.beginPath();
const sliceWidth = (WIDTH * 1.0) / bufferLength;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
let v = dataArray[i] / 128.0;
let y = (v * HEIGHT) / 2;
if (i === 0) {
canvasCtx.moveTo(x, y);
} else {
canvasCtx.lineTo(x, y);
}
x += sliceWidth;
}
canvasCtx.lineTo(canvas.width, canvas.height / 2);
canvasCtx.stroke();
};
draw();
} else if (visualSetting == "frequencybars") {
analyser.fftSize = 256;
const bufferLengthAlt = analyser.frequencyBinCount;
console.log(bufferLengthAlt);
// See comment above for Float32Array()
const dataArrayAlt = new Uint8Array(bufferLengthAlt);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
const drawAlt = function () {
drawVisual = requestAnimationFrame(drawAlt);
analyser.getByteFrequencyData(dataArrayAlt);
canvasCtx.fillStyle = "rgb(0, 0, 0)";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
const barWidth = (WIDTH / bufferLengthAlt) * 2.5;
let barHeight;
let x = 0;
for (let i = 0; i < bufferLengthAlt; i++) {
barHeight = dataArrayAlt[i];
canvasCtx.fillStyle = "rgb(" + (barHeight + 100) + ",50,50)";
canvasCtx.fillRect(
x,
HEIGHT - barHeight / 2,
barWidth,
barHeight / 2
);
x += barWidth + 1;
}
};
drawAlt();
} else if (visualSetting == "off") {
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
canvasCtx.fillStyle = "red";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
}
}
function voiceChange() {
distortion.oversample = "4x";
biquadFilter.gain.setTargetAtTime(0, audioCtx.currentTime, 0);
const voiceSetting = voiceSelect.value;
console.log(voiceSetting);
if (echoDelay.isApplied()) {
echoDelay.discard();
}
// When convolver is selected it is connected back into the audio path
if (voiceSetting == "convolver") {
biquadFilter.disconnect(0);
biquadFilter.connect(convolver);
} else {
biquadFilter.disconnect(0);
biquadFilter.connect(gainNode);
if (voiceSetting == "distortion") {
distortion.curve = makeDistortionCurve(400);
} else if (voiceSetting == "biquad") {
biquadFilter.type = "lowshelf";
biquadFilter.frequency.setTargetAtTime(1000, audioCtx.currentTime, 0);
biquadFilter.gain.setTargetAtTime(25, audioCtx.currentTime, 0);
} else if (voiceSetting == "delay") {
echoDelay.apply();
} else if (voiceSetting == "off") {
console.log("Voice settings turned off");
}
}
}
function createEchoDelayEffect(audioContext) {
const delay = audioContext.createDelay(1);
const dryNode = audioContext.createGain();
const wetNode = audioContext.createGain();
const mixer = audioContext.createGain();
const filter = audioContext.createBiquadFilter();
delay.delayTime.value = 0.75;
dryNode.gain.value = 1;
wetNode.gain.value = 0;
filter.frequency.value = 1100;
filter.type = "highpass";
return {
apply: function () {
wetNode.gain.setValueAtTime(0.75, audioContext.currentTime);
},
discard: function () {
wetNode.gain.setValueAtTime(0, audioContext.currentTime);
},
isApplied: function () {
return wetNode.gain.value > 0;
},
placeBetween: function (inputNode, outputNode) {
inputNode.connect(delay);
delay.connect(wetNode);
wetNode.connect(filter);
filter.connect(delay);
inputNode.connect(dryNode);
dryNode.connect(mixer);
wetNode.connect(mixer);
mixer.connect(outputNode);
},
};
}
// Event listeners to change visualize and voice settings
visualSelect.onchange = function () {
window.cancelAnimationFrame(drawVisual);
visualize();
};
voiceSelect.onchange = function () {
voiceChange();
};
mute.onclick = voiceMute;
function voiceMute() {
if (mute.id === "") {
gainNode.gain.value = 0;
mute.id = "activated";
mute.innerHTML = "Unmute";
} else {
gainNode.gain.value = 0;
mute.id = "";
mute.innerHTML = "Mute";
}
}
}