錄製用戶的音頻,視屏 navigator.mediaDevices.getUserMedia

google 文檔 HACKS 文檔 相關代碼html

獲取本地的音頻

<input type="file" accept="audio/*" capture="microphone" id="recorder">
  <audio id="player" controls></audio>
  <script>
    var recorder = document.getElementById('recorder');
    var player = document.getElementById('player')

    recorder.addEventListener('change', function (e) {
      var file = e.target.files[0];
      // Do something with the audio file.
      player.src = URL.createObjectURL(file);
    });
  </script>

獲取麥克風聲音

聲音極小git

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        a,
        button {
            border: 0;
            background-color: #448aff21;
            text-decoration: none;
            padding: 10px;
            border-radius: 2px;
            color: #448aff !important;
        }
    </style>
</head>

<body style="margin-top: 20px;">
    <a id="download">Download</a>
    <button id="start">Start</button>
    <button id="stop">Stop</button>
    <script>
        let l = console.log
        navigator.permissions.query({
            name: 'microphone'
        }).then(function (result) {
            if (result.state == 'granted') { // 用戶以前已授予對麥克風的訪問權
                l('ok')
            } else if (result.state == 'prompt') { // 用戶還沒有授予訪問權,調用 getUserMedia 時將會收到提示
                l('ready')
            } else if (result.state == 'denied') { // 系統或用戶已顯式屏蔽對麥克風的訪問權,您將沒法得到對其的訪問權
                l('...')
            }
            result.onchange = function () {
                l('change..')
            };
        });
        const downloadLink = document.getElementById('download');
        const stopButton = document.getElementById('stop');
        const startButton = document.getElementById('start');

        navigator.mediaDevices.getUserMedia({
                audio: true,
                video: false
            })
            .then(stream => {
                stopButton.addEventListener('click', e => {
                    mediaRecorder.stop();
                })

                startButton.addEventListener('click', e => {
                    mediaRecorder.start();
                })
                const recordedChunks = [];
                const mediaRecorder = new MediaRecorder(stream);

                mediaRecorder.addEventListener('dataavailable', function (e) {
                    if (e.data.size > 0) {
                        recordedChunks.push(e.data);
                    }
                });

                mediaRecorder.addEventListener('stop', function () {
                    l('暫停')
                    downloadLink.href = URL.createObjectURL(new Blob(recordedChunks));
                    downloadLink.download = 'acetest.wav';
                });

                mediaRecorder.addEventListener('start', e => {
                    l('開始')
                })
            });
    </script>
</body>

鑲嵌在 audio元素裏面

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        a,
        button {
            border: 0;
            background-color: #448aff21;
            text-decoration: none;
            padding: 10px;
            border-radius: 2px;
            color: #448aff !important;
        }
    </style>
</head>

<body style="margin-top: 20px;">
    <button id="start">Start</button>
    <button id="stop">Stop</button>
    <div>
        <audio id="audio" controls></audio>
    </div>
    <script>
        let l = console.log
        const stopButton = document.getElementById('stop');
        const startButton = document.getElementById('start');

        navigator.mediaDevices.getUserMedia({
                audio: true,
                // video: true
            })
            .then(stream => {
                stopButton.addEventListener('click', e => {
                    mediaRecorder.stop();
                })

                startButton.addEventListener('click', e => {
                    mediaRecorder.start();
                })
                const recordedChunks = [];
                const mediaRecorder = new MediaRecorder(stream);
                mediaRecorder.addEventListener('dataavailable', function (e) {
                    if (e.data.size > 0) {
                        recordedChunks.push(e.data);
                    }
                });

                mediaRecorder.addEventListener('stop', function () {
                    l('暫停')
                    var audio = document.getElementById('audio');
                    audio.src = URL.createObjectURL(new Blob(recordedChunks));
                    audio.play();
                });

                mediaRecorder.addEventListener('start', e => {
                    l('開始')
                })
            });
    </script>
</body>

錄製視頻 github地址

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      a,
      button {
        border: 0;
        background-color: #448aff21;
        text-decoration: none;
        padding: 10px;
        border-radius: 2px;
        color: #448aff !important;
      }
    </style>
  </head>

  <body style="margin-top: 20px;">
    <button id="start">Start</button> <button id="stop">Stop</button>
    <div>
      <p>live. <span class="timer"></span></p>
      <video
        width="600"
        id="live"
        style="box-sizing: border-box; border: 4px solid #f48"
      ></video>
    </div>
    <script>
      let l = console.log;
      let n = 0;

      let mediaRecorder;
      let timer;
      const stopButton = document.getElementById("stop");
      const startButton = document.getElementById("start");

      navigator.mediaDevices
        .getUserMedia({
          audio: true,
          video: true,
        })
        .then(stream => {
          let liveVideo = document.getElementById("live");
          // liveVideo.src = URL.createObjectURL(stream); // 你會看到一些警告
          liveVideo.srcObject = stream;
          liveVideo.play();

          stopButton.addEventListener("click", stopLive);
          startButton.addEventListener("click", e => {
            startLive(stream);
          });
        });

      // 顯示錄製的秒數
      function logger() {
        const timerEl = document.querySelector(".timer");
        timer = setInterval(() => {
          n += 1;
          timerEl.textContent = `${n}s`;
        }, 1000);
      }

      // 暫停後下載視頻
      function downLoadVideo(chunks) {
        let downloadLink = document.createElement("a");
        downloadLink.href = URL.createObjectURL(
          new Blob(chunks, {
            type: "application/video",
          })
        );
        // downloadLink.download = 'live.webm';
        downloadLink.download = "live.ogg";
        // downloadLink.download = 'live.mp4';
        downloadLink.click();
      }

      // 結束錄製
      function stopLive() {
        clearInterval(timer);
        n = 0;
        if (mediaRecorder) {
          mediaRecorder.stop();
        } else {
          alert("尚未開始。");
        }
      }

      function startLive(stream) {
        logger();
        let recordedChunks = [];
        mediaRecorder = new MediaRecorder(stream);
        mediaRecorder.start();

        mediaRecorder.addEventListener("dataavailable", function(e) {
          if (e.data.size > 0) recordedChunks.push(e.data);
        });

        mediaRecorder.addEventListener("stop", function() {
          l("暫停 自動下載");
          downLoadVideo(recordedChunks);
        });

        mediaRecorder.addEventListener("start", e => {
          l("開始 錄製");
        });
      }
    </script>
  </body>
</html>
相關文章
相關標籤/搜索