前端录屏屏幕 Demo

代码实现了如下功能:录制-保存、录制-回放、直播(边录边回放)

<html>
  <head>
    <title>Capturetitle>
    <meta charset="utf8">
  head>
  <body>
    <button id="capture">Startbutton>

    <video id="video">video>
    <script>
      (function() {
        console.log(MediaRecorder.isTypeSupported("video/webm"))
        console.log(MediaRecorder.isTypeSupported("video/mp4"))
        console.log(MediaRecorder.isTypeSupported("video/mp4;codecs=avc1"))
      })()
    script>
    <script>
      var RECORDING_ONGOING = false;
        var recordingToggle = document.getElementById("capture"); // The button

        recordingToggle.addEventListener("click", function () {
          RECORDING_ONGOING = !RECORDING_ONGOING; // Start / Stop recording
          if (RECORDING_ONGOING) {
            recordingToggle.innerHTML = "Stop";
            startRecording(); // Start the recording
          } else {
            recordingToggle.innerHTML = "Start";
            stopRecording(); // Stop screen recording
          }
        });
    script>

    <script>
      var blob, mediaRecorder = null;
      var chunks = [];

      async function startRecording() {
        // 获取权限,会有弹窗让用户选择和确认
        stream = await navigator.mediaDevices.getDisplayMedia(
          { video: { mediaSource: "screen" }, audio: true }
        );

        deviceRecorder = new MediaRecorder(stream, { mimeType: "video/webm" });
        deviceRecorder.ondataavailable = (e) => {
          if (e.data.size > 0) {
            chunks.push(e.data);
          }
        }
        deviceRecorder.onstop = () => {
          chunks = [];
        }
        deviceRecorder.start(250)
      }

      function stopRecording() {
        var filename = window.prompt("File name", "video"); // Ask the file name

        deviceRecorder.stop(); // Stopping the recording
        blob = new Blob(chunks, { type: "video/webm" })
        chunks = [] // Resetting the data chunks
        var dataDownloadUrl = URL.createObjectURL(blob);

        // Downloadin it onto the user's device
        let a = document.createElement('a')
        a.href = dataDownloadUrl;
        a.download = `${filename}.webm`
        a.click()

        URL.revokeObjectURL(dataDownloadUrl)

        replay(blob)
      }

      // 回放录制内容
      function replay(blob) {
        const video = document.getElementById("video");
        video.src = window.URL.createObjectURL(blob);
        video.srcObject = null;
        video.controls = true;
        video.play();
      }

      // 直播
      function live() {
        const video = document.getElementById("video");
        video.srcObject = window.stream;
        video.controls = true;
        video.play();
      }
    script>
  body>
html>

你可能感兴趣的:(前端,前端,javascript,开发语言,录屏)