Skip to content

Instantly share code, notes, and snippets.

@spite
Created September 13, 2019 11:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save spite/368d11c38be78a72ff4afb030ea64b07 to your computer and use it in GitHub Desktop.
Save spite/368d11c38be78a72ff4afb030ea64b07 to your computer and use it in GitHub Desktop.
function r() {
let mediaRecorder;
let recordedBlobs;
let startTime = 0;
function handleDataAvailable(event) {
console.log('on data available')
if (event.data && event.data.size > 0) {
recordedBlobs.push(event.data);
}
}
function startRecording(stream) {
recordedBlobs = [];
let options = {mimeType: 'video/webm;codecs=vp9'};
if (!MediaRecorder.isTypeSupported(options.mimeType)) {
console.error(`${options.mimeType} is not Supported`);
options = {mimeType: 'video/webm;codecs=vp8'};
if (!MediaRecorder.isTypeSupported(options.mimeType)) {
console.error(`${options.mimeType} is not Supported`);
options = {mimeType: 'video/webm'};
if (!MediaRecorder.isTypeSupported(options.mimeType)) {
console.error(`${options.mimeType} is not Supported`);
options = {mimeType: ''};
}
}
}
try {
mediaRecorder = new MediaRecorder(stream, options);
} catch (e) {
console.error('Exception while creating MediaRecorder:', e);
return;
}
console.log('Created MediaRecorder', mediaRecorder, 'with options', options);
mediaRecorder.onstop = (event) => {
console.log('Recorder stopped: ', event);
};
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start(10); // collect 10ms of data
console.log('MediaRecorder started', mediaRecorder);
startTime = performance.now();
}
let duration = 0;
function stopRecording() {
mediaRecorder.stop();
duration = performance.now() - startTime;
console.log('Recorded Blobs: ', recordedBlobs, duration);
}
async function download() {
const blob = new Blob(recordedBlobs, {type: 'video/webm'});
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'test.webm';
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 100);
}
return {
start: startRecording,
stop: stopRecording,
download
}
}
var a = r();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment