-
Notifications
You must be signed in to change notification settings - Fork 0
/
audioProcessing.html
398 lines (378 loc) · 13.3 KB
/
audioProcessing.html
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<title>Audio Processing</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
1. Choose a file:<br>
<input type="file" id="file"> or <button id="rec" style="width: 200px;">Record from your microphone</button><br>
2. Choose an effect:
<select id="selectEffect">
<option value="----" selected="selected">----</option>
<option value="chunkSort">Chunk Sort</option>
<option value="chopper">Chopper</option>
</select><br>
3. Configure the effect:<br>
<div class="effectsContainer">
<div id="chunkSortContainer" class="effect">
This will split audio into 'chunks' and sort them by loudness.<br>
First set a chunk size:<br>
Chunk size (in seconds): <input id="chunk" value="0.05"><br>
Crossfade length (Needs to be less than Chunk size [less than 1/2 of chunk size for overlap]): <input id="cross" value="0.008333333333333333333333333333"><br>
Sort loudest to quietest?: <input id="sortOrder" type="checkbox" checked><br>
Mode:
<select id="algorithmMode">
<option value="xfadeOverlap" selected="selected">Crossfade (favor volume order)</option>
<option value="xfadeNoOverlap">Crossfade (favor original sample length)</option>
<option value="noXfade">No crossfade (sounds clicky)</option>
</select><br>
<button>Process</button>
</div>
<div id="chopperContainer" class="effect">
This will mute the audio during each second chunk to create a choppy effect.
First chunk length: <input id="firstChunk" value="0.025"><br>
Second chunk length: <input id="secondChunk" value="0.01666666666666666666666666667"><br>
Fade length: <input id="chopperFade" value="0.0001"><br>
Elongate instead of mute: <input id="elongate" type="checkbox" checked><br>
<button>Process</button>
</div>
<div id="fractalizeContainer" class="effect">
Overlay copies of source audio played at different speeds<br>
<button>Process</button>
</div>
<div id="ringModContainer" class="effect">
Multiply left channel and right channel together to get the sum and difference of their frequencies. Requires a stereo input.<br>
<button>Process</button>
</div>
</div>
4. Process the audio:<button id="processButton">Process</button><br>
5. Listen again:<button id="playButton">Play Again</button><br>
6. Save the audio to your computer:<button id="saveButton">Save</button>
<script>
window.module = {};
</script>
<!-- https://github.com/mattdiamond/Recorderjs -->
<script src="recorder.js"></script>
<!-- https://github.com/Jam3/audiobuffer-to-wav -->
<script src="index.js"></script>
<script>
// hack to get this commonjs module.
const bufferToWav = module.exports;
const $ = document.querySelector.bind(document);
const fileSelect = $('#file');
const ctx = new AudioContext();
let sampleRate = 44100;
let buffer;
//the root square of the average of the square of each value
//inclusive start, exclusive end
//assumes start < end
function rootMeanSquare(data, start, end) {
const length = end - start;
let rms = 0;
for (let t = start; t < end; t++) {
const value = data[t];
rms += value * value;
}
rms /= length;
rms = Math.sqrt(rms);
return rms;
}
// Utility function to convert a mono function to support stereo processing
function stereoize(monoFunc) {
let stereoFunc = function (leftData, rightData) {
let result = {};
result.left = monoFunc(leftData);
if (rightData) {
result.right = monoFunc(rightData);
}
return result;
};
return stereoFunc;
}
connectButtonToPCMFunction($('#ringModContainer button'), ringModChangePCM);
function ringModChangePCM(leftData, rightData) {
let longerChannel;
let shorterChannel;
if (leftData.length > rightData.length) {
longerChannel = leftData;
shorterChannel = rightData;
} else {
longerChannel = rightData;
shorterChannel= leftData;
}
for (let i=0; i<shorterChannel.length; i++) {
shorterChannel[i] = shorterChannel[i] * longerChannel[i];
}
return { left: shorterChannel };
}
connectButtonToPCMFunction($('#fractalizeContainer button'), stereoize(fractalizeChangePCM));
function fractalizeChangePCM(data) {
const finalLength = data.length;
const iterations = 10;
const dataArray = [];
dataArray.push(data.slice());
let currentData = data;
for (let i=0; i<iterations; i++) {
const spedUp = new Float32Array(Math.floor(currentData.length/2));
for (let j=0; j<spedUp.length; j++) {
spedUp[j] = 0.35 * (currentData[2 * j] + currentData[2 * j + 1]);
}
dataArray.push(spedUp);
currentData = spedUp;
}
const newBuffer = new Float32Array(finalLength);
for (let i=0; i<finalLength; i++) {
let total = 0;
for (let j=0; j<iterations+1; j++) {
let currentData = dataArray[j];
total += currentData[i%currentData.length] / (Math.pow(2, j + 1));
}
newBuffer[i] = total;
}
return newBuffer;
}
connectButtonToPCMFunction($('#chopperContainer button'), stereoize(chopperChangePCM));
function chopperChangePCM(data) {
let firstChunkLength = parseFloat($('#firstChunk').value);
let secondChunkLength = parseFloat($('#secondChunk').value);
let elongate = document.querySelector('#elongate').value;
let chopCycleLength = firstChunkLength + secondChunkLength;
let crossfadeLength = parseFloat($('#chopperFade').value);
const newBuffer = elongate ? new Float32Array(chopCycleLength/firstChunkLength * data.length) : new Float32Array(data.length);
// i indexes data, j indexes newBuffer
let i=0;
for (let j=0; j<newBuffer.length; j++) {
let timeInSeconds = j/sampleRate;
let completedCycles = Math.floor(timeInSeconds/chopCycleLength);
let secsIntoCycle = timeInSeconds - chopCycleLength * completedCycles;
if (secsIntoCycle < firstChunkLength) {
let fadeScalar = 1;
if (secsIntoCycle < crossfadeLength) {
fadeScalar = secsIntoCycle/crossfadeLength;
} else if (secsIntoCycle > firstChunkLength - crossfadeLength) {
fadeScalar = (firstChunkLength - secsIntoCycle)/crossfadeLength;
}
newBuffer[j] = fadeScalar * data[i];
} else {
if (elongate) {
while (secsIntoCycle < chopCycleLength) {
j++;
secsIntoCycle = j/sampleRate - chopCycleLength * completedCycles;
}
j--; //decrement once since it will increment at the loop
}
}
i++;
}
return newBuffer;
}
connectButtonToPCMFunction($('#chunkSortContainer button'), stereoize(audioSortChangePCM));
function audioSortChangePCM(data) {
// just reverse it
//data.reverse();
// MLG BLAST IT
// const len = data.length;
// for (let x = 0; x < len; x++) {
// data[x] = data[x] * 10;
// }
// sort sections by loudness
let chunkSize = parseFloat($('#chunk').value);
if (isNaN(chunkSize) || chunkSize <= 0) {
alert('invalid chunk size, setting to 0.05');
chunkSize = 0.05;
}
let algorithmMode = document.querySelector('#algorithmMode').value;
let crossfadeLength = parseFloat($('#cross').value);
if (isNaN(crossfadeLength) || crossfadeLength <= 0) {
alert('invalid crossfade size, setting to 0.02');
crossfadeLength = 0.02;
}
let crossfadeSamples = Math.floor(crossfadeLength * sampleRate);
let crossfadeInArray = [];
for (let i=0; i<crossfadeSamples; i++) {
crossfadeInArray.push(i/crossfadeSamples);
}
let crossfadeOutArray = crossfadeInArray.slice().reverse()
const frames = [];
const len = data.length;
let v = 0;
let chunkIndex = 0;
while (v < len) {
let start = Math.floor(chunkIndex * chunkSize * sampleRate);
let end = Math.floor(start + chunkSize * sampleRate);
let frameSize = end-start;
if (end >= len) {
//abandon any leftover data that doesn't fit
break;
}
let rms = rootMeanSquare(data, start, end);
frames.push({offset: v, loudness: rms, frameSize: frameSize});
v = end;
chunkIndex++;
}
if (algorithmMode === 'xfadeNoOverlap') {
//remove the last frame so we know we have some data after the second to last frame for fading
frames.pop();
}
frames.sort(function(a, b) {
return $('#sortOrder').checked ? b.loudness - a.loudness : a.loudness - b.loudness;
});
const newBuffer = new Float32Array(len);
const numFrames = frames.length;
if (algorithmMode === 'xfadeNoOverlap') {
let i = 0;
// special case for first frame
const frame = frames[0];
const offset = frame.offset;
for (let w = 0; w < frame.frameSize; w++) {
newBuffer[i] = data[offset + w];
i++;
}
for (let x = 1; x < numFrames; x++) {
const frame = frames[x];
const prevframe = frames[x-1];
//crossfade
for (let y = 0; y < crossfadeSamples; y++) {
newBuffer[i] = data[frame.offset + y]*crossfadeInArray[y] + data[prevframe.offset + prevframe.frameSize + y]*crossfadeOutArray[y];
i++;
}
for (let z = crossfadeSamples; z < frame.frameSize; z++) {
newBuffer[i] = data[frame.offset + z];
i++;
}
}
} else if (algorithmMode === 'xfadeOverlap') {
let i = 0;
// special case for first frame
const frame = frames[0];
const offset = frame.offset;
for (let v = 0; v < frame.frameSize-crossfadeSamples; v++) {
newBuffer[i] = data[offset + v];
i++;
}
for (let w = 1; w < numFrames-1; w++) {
const prevFrame = frames[w-1];
const frame = frames[w];
const nextFrame = frames[w-1];
// crossfade into frame and out of prev frame
for (let x = 0; x < crossfadeSamples; x++) {
newBuffer[i] = data[frame.offset + x]*crossfadeInArray[x] + data[prevFrame.offset + prevFrame.frameSize - crossfadeSamples + x]*crossfadeOutArray[x];
i++;
}
// frame
for (let y = crossfadeSamples; y < frame.frameSize-crossfadeSamples; y++) {
newBuffer[i] = data[frame.offset + y];
i++;
}
}
} else {
let i = 0;
for (let x = 0; x < numFrames; x++) {
const frame = frames[x];
const offset = frame.offset;
for (let z = 0; z < frame.frameSize; z++) {
newBuffer[i] = data[offset + z];
i++;
}
}
}
return newBuffer;
}
function playBuffer() {
if (buffer) {
const sourceNode = ctx.createBufferSource();
sourceNode.buffer = buffer;
sourceNode.connect(ctx.destination);
sourceNode.start();
} else {
alert("No audio to play. Either select a file or use a mic to record above.");
}
}
fileSelect.addEventListener('change', function(e) {
const file = e.target.files[0];
sampleRate = 44100;
const context = new OfflineAudioContext(2, 1, sampleRate);
const reader = new FileReader();
reader.onload = function(e) {
context.decodeAudioData(e.target.result, function(retBuffer) {
buffer = retBuffer;
}, function(err) {
console.log(err);
});
};
reader.readAsArrayBuffer(file);
});
function connectButtonToPCMFunction(button, changePCMFunction) {
button.addEventListener('click', function() {
let leftChannelData = buffer.getChannelData(0);
let rightChannelData;
try {
rightChannelData = buffer.getChannelData(1);
} catch(e) {}
let result = changePCMFunction(leftChannelData, rightChannelData);
let stereo = Boolean(result.right); // should it be result.right.length instead so an empty array leads to mono?
let newBuffer;
if (stereo) {
newBuffer = ctx.createBuffer(2, Math.max(result.left.length, result.right.length), 44100);
} else {
newBuffer = ctx.createBuffer(1, result.left.length, 44100);
}
newBuffer.getChannelData(0).set(result.left);
try {
newBuffer.getChannelData(1).set(result.right);
} catch(e) {}
buffer = newBuffer;
playBuffer();
});
}
$('#playButton').addEventListener('click', function() {
playBuffer();
});
$('#saveButton').onclick = function() {
const wav = bufferToWav(buffer);
const blob = new window.Blob([ new DataView(wav) ], {
type: 'audio/wav'
});
const url = window.URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = 'audio.wav';
anchor.click();
window.URL.revokeObjectURL(url);
};
let recordingState = 'stopped';
let currentStream;
let rec;
const recordBtn = $('#rec');
recordBtn.addEventListener('click', function() {
if (recordingState === 'recording') {
recordingState = 'stopped';
currentStream.getTracks()[0].stop();
recordBtn.textContent = 'Record from your microphone';
rec.stop();
rec.getBuffer(function(buffers) {
sampleRate = ctx.sampleRate;
var newBuffer = ctx.createBuffer(buffers.length, buffers[0].length, ctx.sampleRate);
for (let x = 0; x < buffers.length; x++) {
newBuffer.getChannelData(x).set(buffers[x]);
}
buffer = newBuffer;
});
} else if (recordingState === 'stopped') {
recordingState = 'preparing';
navigator.mediaDevices.getUserMedia({audio: true}).then(function(stream) {
currentStream = stream;
recordingState = 'recording';
recordBtn.textContent = 'Stop recording';
const source = ctx.createMediaStreamSource(stream);
rec = new Recorder(source);
rec.record();
}).catch(function(e) {
console.log('Error recording!', e);
recordingState = 'stopped';
});
}
});
</script>
</body></html>