JSFiddle - React, Tailwind, and code Playground

by agcty

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Simple Screen Record!</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/comlinkjs@3.0.2/umd/comlink.js"></script>
    <script src="/script.js" async></script>
    <!-- import the webpage's stylesheet -->
    <link rel="stylesheet" href="/style.css">
  </head>  
  <body>
    <button id="captureBtn">Start Recording</button>
    <button id="stopBtn">Stop Capture</button>
    <a id="download" href="#">Download</a>
  </body>
</html>

CSS

/* CSS files add styling rules to your content */

body {
    font-family: "Benton Sans", "Helvetica Neue", helvetica, arial, sans-serif;
    margin: 2em;
  }
  
  h1 {
    font-style: italic;
    color: #373fff;
  }
  
  video {
    width: 640px;
    height: 480px;
  }
  
  button {
    margin: 1em;
    padding: 1em;
  }

JavaScript

const captureBtn = document.getElementById("captureBtn");
const download = document.getElementById("download");
const stopBtn = document.getElementById("stopBtn");

var rec = null;
captureBtn.onclick = async () => {
  desktopStream = await navigator.mediaDevices.getDisplayMedia({
    video: true,
    audio: true,
  });

  voiceStream = await navigator.mediaDevices.getUserMedia({
    video: false,
    audio: true,
  });

  // when line below commmented, screen recording works as expected and onstop gets called
  desktopStream.addTrack(voiceStream.getAudioTracks()[0]);

  blobs = [];

  rec = new MediaRecorder(desktopStream, {
    mimeType: "video/webm; codecs=vp8,opus",
  });

  rec.ondataavailable = (e) => blobs.push(e.data);
  rec.onstop = async () => {
    voiceStream.getTracks().forEach((s) => s.stop());
    desktopStream.getTracks().forEach((s) => s.stop());
    desktopStream.getTracks().forEach((s) => s.stop());
    desktopStream = null;

    //blobs.push(MediaRecorder.requestData());
    blob = new Blob(blobs, {
      type: "video/webm",
    });
    let url = window.URL.createObjectURL(blob);
    download.href = url;
    download.download = "test.webm";
    download.style.display = "block";
  };
  rec.start();
};

stopBtn.onclick = () => {
  rec.stop();
};