-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrecord.js
30 lines (23 loc) · 1.13 KB
/
record.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
import { convertAudioBufferToWavBlob, downloadBlob, initButtonListener } from './utils.js';
navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
// Initialize variables now that media devices are ready
const mediaRecorder = new MediaRecorder(stream);
let audioChunks = [];
initButtonListener(mediaRecorder);
// Listen for new audio data chunks and add them to our array
mediaRecorder.addEventListener('dataavailable', (event) => {
audioChunks.push(event.data);
});
// When the recording has stopped, process and download our audio
mediaRecorder.addEventListener('stop', async () => {
const webaBlob = new Blob(audioChunks, { type: 'audio/webm;codecs=opus' });
// Convert the blob into binary data
const arrayBuffer = await webaBlob.arrayBuffer();
// Use AudioContext to decode our array buffer into an audio buffer
const audioContext = new AudioContext();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
const wavBlob = await convertAudioBufferToWavBlob(audioBuffer);
downloadBlob(wavBlob, 'recording');
audioChunks = []; // Clear cached chunks
});
});