纯前端实现录屏并保存视频到本地【转载】

转载地址:https://mp.weixin.qq.com/s/ryAF9IXRsaPs01xSHG-AiA

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>共享屏幕</button>
    <script>
      const button = document.querySelector("button");
      button.addEventListener("click", async () => {
        const stream = await navigator.mediaDevices.getDisplayMedia({
          video: true,
        });

        const mime = MediaRecorder.isTypeSupported("video/webm;codecs=h264")
          ? "video/webm;codecs=h264"
          : "video/webm";

        const mediaRecorder = new MediaRecorder(stream, { mimeType: mime });

        const chunks = [];
        mediaRecorder.addEventListener("dataavailable", function (e) {
          chunks.push(e.data);
        });

        mediaRecorder.addEventListener("stop", () => {
          const blob = new Blob(chunks, { type: chunks[0].type });
          const url = URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = "video.mp4";
          a.click();
        });
        mediaRecorder.start();
      });
    </script>
  </body>
</html>
posted @ 2023-11-08 14:44  xustch  阅读(50)  评论(0编辑  收藏  举报