Simple video recording in the browser

While experimenting with the JavaScript MediaRecorder API in the browser, I put together this abstraction for recording.

Here's an example usage: recording a 5s video, then printing the blob object URL

getSimpleRecorder().then(recorder => {
  recorder.promiseDownloadUrl.then(console.log);
  recorder.start();
  setTimeout(() => {
    recorder.stop();
  }, 5000);
});

And here's the abstraction of MediaRecorder:

const getSimpleRecorder = () => navigator.mediaDevices.getUserMedia({
  audio: true,
  video: {
    width: { ideal: 1080, max: 1920 },
    height: { ideal: 1080, max: 1920 },
    aspectRatio: 1,
    frameRate: { min: 24, ideal: 30, max: 30 },
    facingMode: "user"
  }
}).then((mediaStream) => {
  const recordingChunks = [];
  const recorder = new MediaRecorder(mediaStream);
  recorder.ondataavailable = (e) => {
    if (e.data.size > 0) recordingChunks.push(e.data);
  };
  const promiseDownloadUrl = new Promise((resolve) => {
    recorder.onstop = () => {
      mediaStream.getTracks().forEach((track) => track.stop());
      const blob = new Blob(recordingChunks, { 'type' : 'video/mp4' });
      const downloadUrl = URL.createObjectURL(blob);
      resolve(downloadUrl);
    };
  });
  return {
    start: () => recorder.start(),
    stop: () => recorder.stop(),
    promiseDownloadUrl
  };
});

Have a lovely day.
© 2023, Graham Macphee.