-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp.mjs
More file actions
300 lines (258 loc) · 10.1 KB
/
Copy pathapp.mjs
File metadata and controls
300 lines (258 loc) · 10.1 KB
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
'use strict';
import {IndexedDBStorage} from './indexeddb-storage.mjs';
import * as visualize from './visualize.mjs';
import { audioBufferToWav } from './wav-utils.mjs';
const DELETE_BUTTON_SELECTOR = '.delete-button';
const DOWNLOAD_BUTTON_SELECTOR = '.download-button';
const RECORDING_DESCRIPTION_SELECTOR = '.recording-description';
const recordButton = document.querySelector('#record');
const recordOutlineEl = document.querySelector('#record-outline');
const soundClips = document.querySelector('.sound-clips');
const clipTemplate = document.querySelector('#clip-template');
document.addEventListener('DOMContentLoaded', init);
// Enable offline support through a ServiceWorker. We register the message
// listener during import time (before DOMContentLoaded), in order to not
// miss messages that are sent during resource loading.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener('message', (event) => {
if (event.data.type === 'reload') {
// The ServiceWorker refreshes cached resources in the background. In
// case of a cache invalidation, the worker sends a message that
// instructs the website to reload.
window.location.reload();
}
});
navigator.serviceWorker.register('./service-worker.js');
}
const CONFIG_RADIOS_SELECTOR = '#config-radios';
const CONFIG_RADIO_TEMPLATE_SELECTOR = '#config-radio-template';
const RECORDING_CONFIGS = [
{ name: "default", param: true },
{
name: "no-effects",
param: {
autoGainControl: false,
echoCancellation: false,
noiseSuppression: false,
}
},
{
name: "agc-only",
param: {
autoGainControl: true,
echoCancellation: false,
noiseSuppression: false,
}
},
];
function populateRecordingConfigurations() {
const configRadioTemplate = document.querySelector(CONFIG_RADIO_TEMPLATE_SELECTOR);
const configRadios = document.querySelector(CONFIG_RADIOS_SELECTOR);
const configParam = new URLSearchParams(window.location.search).get('config');
for (const [i, {name, param}] of RECORDING_CONFIGS.entries()) {
const radio = configRadioTemplate.content.firstElementChild.cloneNode(true);
const input = radio.querySelector('input');
const label = radio.querySelector('label');
input.id = `radio-${name}`;
label.textContent = `${name} (${JSON.stringify(param)})`;
label.setAttribute('for', input.id);
label.recordingParam = param;
// Check if this config matches the query param, otherwise default to the first one
if (configParam) {
if (name === configParam) {
input.checked = true;
}
} else if (i === 0) {
input.checked = true;
}
configRadios.appendChild(radio);
}
}
function getSelectedRecordingConfig() {
const configRadios = document.querySelector(CONFIG_RADIOS_SELECTOR);
const selectedRadio = configRadios.querySelector('input:checked');
const label = configRadios.querySelector(`label[for="${selectedRadio.id}"]`);
return {text: label.textContent, param: label.recordingParam};
}
/** Initializes the web application. */
async function init() {
/* global mdc */ // Material Components Web scripts are loaded in index.html.
new mdc.iconButton.MDCIconButtonToggle(recordButton);
recordButton.onclick = () => startRecording({storage});
populateRecordingConfigurations();
const storage = new IndexedDBStorage();
await storage.open();
for await (const [id, {recordingDescription, blob}] of storage.readAll()) {
const clipContainer = insertClip();
finalizeClip({clipContainer, id, recordingDescription, blob, storage});
}
if (new URLSearchParams(window.location.search).get('test') === '1') {
runTest();
}
}
/**
* Inserts a new audio clip at the top of the list.
*
* @return {HTMLElement} Container element of the audio clip.
*/
function insertClip() {
const clipContainer = clipTemplate.content.firstElementChild.cloneNode(true);
soundClips.prepend(clipContainer);
return clipContainer;
}
/** Finalizes a clip by replacing the visualization with the audio element. */
function finalizeClip({clipContainer, blob, id, recordingDescription, storage}) {
clipContainer.querySelector(RECORDING_DESCRIPTION_SELECTOR).textContent = recordingDescription;
clipContainer.querySelector(DELETE_BUTTON_SELECTOR).onclick = () => {
clipContainer.parentNode.removeChild(clipContainer);
storage.delete(parseInt(id));
};
clipContainer.querySelector(DOWNLOAD_BUTTON_SELECTOR).onclick = async () => {
const arrayBuffer = await blob.arrayBuffer();
const audioCtx = new AudioContext();
try {
const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
const wavView = audioBufferToWav(audioBuffer);
const wavBlob = new Blob([wavView], { type: 'audio/wav' });
const url = URL.createObjectURL(wavBlob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = `${recordingDescription.replace(/[:\/\s]/g, '_')}.wav`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
} catch (e) {
console.error('Error converting to WAV:', e);
alert('Failed to convert audio to WAV');
} finally {
await audioCtx.close();
}
};
clipContainer.querySelector('audio').src = URL.createObjectURL(blob);
clipContainer.classList.remove('clip-recording');
}
/** Accesses the device's microphone and returns an audio stream.
*
* @return {Promise<MediaStream>|null} Promise with MediaStream or
* null on error.
*/
async function getAudioStream(param) {
try {
return await navigator.mediaDevices.getUserMedia({audio: param});
} catch (e) {
console.error(e);
return null;
}
}
/**
* Starts recording an audio snippet in-memory and visualizes the recording
* waveform.
*/
async function startRecording({storage}) {
const config = getSelectedRecordingConfig();
const chunks = [];
const stream = await getAudioStream(config.param);
if (!stream) {
return; // Permissions have not been granted or an error occurred.
}
const clipContainer = insertClip();
const canvas = clipContainer.querySelector('canvas');
canvas.width = clipContainer.offsetWidth;
const recordingDescription = `${(new Date()).toLocaleString()}\u2003${config.text}`;
clipContainer.querySelector(RECORDING_DESCRIPTION_SELECTOR).textContent = recordingDescription;
const outlineIndicator = new visualize.OutlineLoudnessIndicator(
recordOutlineEl);
const waveformIndicator = new visualize.WaveformIndicator(canvas);
// Start recording the microphone's audio stream in-memory.
const mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = ({data}) => {
chunks.push(data);
};
mediaRecorder.onstop = async () => {
outlineIndicator.hide();
recordButton.onclick = () => startRecording({storage});
const blob = new Blob(chunks, {type: mediaRecorder.mimeType});
console.log({recordingDescription, blob});
const id = await storage.save({recordingDescription, blob});
finalizeClip({clipContainer, id, blob, recordingDescription, storage});
};
mediaRecorder.start();
recordButton.onclick = () => {
// Stop the audio track to remove the browser's recording indicator and
// stop the MediaRecorder.
stream.getTracks().forEach((track) => {
track.stop();
});
};
visualizeRecording({stream, outlineIndicator, waveformIndicator});
}
/** Visualizes the audio with a waveform and a loudness indicator. */
function visualizeRecording({stream, outlineIndicator, waveformIndicator}) {
// Use AnalyserNode to compute the recorded audio's power to visualize
// loudness.
const audioCtx = new AudioContext();
const source = audioCtx.createMediaStreamSource(stream);
const analyser = audioCtx.createAnalyser();
analyser.fftSize = 32; // Smallest possible FFT size for cheaper computation.
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
source.connect(analyser);
waveformIndicator.drawCenterLine();
/** Repeatedly draws the waveform and loudness indicator. */
function draw() {
if (!stream.active) {
// Stop drawing loop once the recording stopped, and release the
// AudioContext. Browsers limit the number of concurrent AudioContexts, so
// failing to close it here leaks one context per recording and, after a
// few dozen recordings, prevents new contexts from starting (the waveform
// stops appearing and playback breaks until the page is refreshed).
audioCtx.close();
return;
}
analyser.getByteFrequencyData(dataArray);
const loudness = visualize.calculateLoudness(dataArray);
outlineIndicator.show(loudness);
waveformIndicator.show(loudness);
requestAnimationFrame(draw);
}
draw();
}
async function runTest() {
// 1. Start recording and playback
recordButton.click();
const playbackSource = document.querySelector('#playback-source');
playbackSource.play();
// 2. After 15 seconds, stop playback
await new Promise((resolve) => setTimeout(resolve, 15000));
playbackSource.pause();
playbackSource.currentTime = 0;
// 3. After another 25 seconds (total 40s), stop recording
await new Promise((resolve) => setTimeout(resolve, 25000));
recordButton.click();
// 4. Download the recorded audio
await new Promise((resolve) => setTimeout(resolve, 1000));
const clip = soundClips.firstElementChild;
const audio = clip.querySelector('audio');
try {
const response = await fetch(audio.src);
const blob = await response.blob();
const arrayBuffer = await blob.arrayBuffer();
const audioCtx = new AudioContext();
const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
const wavView = audioBufferToWav(audioBuffer);
const wavBlob = new Blob([wavView], { type: 'audio/wav' });
const url = URL.createObjectURL(wavBlob);
const a = document.createElement('a');
a.href = url;
a.download = 'recorded_audio.wav';
document.body.appendChild(a);
a.click();
// Clean up
await audioCtx.close();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (e) {
console.error('Test failed to download WAV:', e);
}
}