JSFiddle - React, Tailwind, and code Playground
JavaScript
var enc = ['ogg', 'webm'];
var extension = "",
mime = '';
enc.forEach(e => !extension &&
(mime = `audio/${e};codecs="opus"`) &&
MediaRecorder.isTypeSupported(mime) &&
(extension = e));
navigator.mediaDevices.getUserMedia({
audio: true
})
.then(stream => {
const chunks = [];
const rec = new MediaRecorder(stream, {
mimeType: mime // use the mimeType we've found
});
// this is not where we build the file, but where we store the chunks
rec.ondataavailable = e => chunks.push(e.data);
rec.onstop = e => {
// stop our gUM stream
stream.getTracks().forEach(t => t.stop());
// NOW create the file
let blob = new Blob(chunks, {
type: mime
});
// we could now send this blob :
// let form = new FormData();
// form.append('file', blob, 'filename.'+extension;
// ... declare xhr
// xhr.send(form);
// but we'll just fetch it for the demo :
let url = URL.createObjectURL(blob);
let au = new Audio(url);
au.controls = true;
document.body.appendChild(au);
au.play();
// and create an downloadable link from it :
let a = document.createElement('a');
a.href = url;
a.download = 'filename.' + extension;
a.innerHTML = 'download';
document.body.appendChild(a);
};
rec.start();
setTimeout(() => rec.stop(), 3000);
});