js的MediaRecorder录音录视频方法笔记

   /**
   * 录音举例说明
   * https://www.cnblogs.com/zaijin-yang/p/17306578.html
   * 通过 web 录制视频(摄像头)并上传
   * https://cloud.tencent.com/developer/article/1818977?areaId=106001
   * 视频录制基础知识-MediaRecorder
   * https://www.jianshu.com/p/ad7dfd50880e
   */

import React, { useState, useEffect } from 'react'


var mediaRecorder
var stream
var chunks = []
export default function App() {
  return (
    
  );
}

function MyRecord() {
  var [fileSize, setFileSize] = useState(0)
  var [url, setUrl] = useState(null)
  /**
   * 录音举例说明
   * https://www.cnblogs.com/zaijin-yang/p/17306578.html
   * 通过 web 录制视频(摄像头)并上传
   * https://cloud.tencent.com/developer/article/1818977?areaId=106001
   * 视频录制基础知识-MediaRecorder
   * https://www.jianshu.com/p/ad7dfd50880e
   */

  async function initRecord() {
    //stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    try {
      stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })
      // const videoElement = document.querySelector('video');
      // videoElement.srcObject = stream;
      //通过调用getUserMedia方法获取摄像头的实时视频流,并将其赋值给srcObject属性,从而在网页上显示实时视频。
      //src适用于加载已有的静态视频文件。
      //srcObject适用于处理实时视频流,比如从摄像头捕获到的视频。
      mediaRecorder = new MediaRecorder(stream);
      mediaRecorder.ondataavailable = event => {
        if (event.data.size > 0) {
          console.log('======ondataavailable事件触发,chunks.length:', chunks.length);
          setFileSize(event.data.size)
          chunks.push(event.data); // 将数据块追加到 chunks 数组中  
        }
      };
      mediaRecorder.onstop = () => {
        console.log('======按下了停止录音键', mediaRecorder.mimeType);
        const blob = new Blob(chunks, { type: mediaRecorder.mimeType }); // 将数据块转换为 Blob  
        // 此时你可以使用 blob 对象,比如上传到服务器或保存到本地文件
        console.log('Blob created:', blob.size);
        const url = URL.createObjectURL(blob); //创建新的URL表示指定的blob对象
        const audio = document.getElementById("aaaa"); //创建标签
        audio.src = url;
        //销毁视频,释放资源URL.revokeObjectURL(url)
      }
    } catch (e) {
      console.log('用户禁止了摄像头权限')
    }
  }
  function startRecord() {
    chunks = []
    mediaRecorder.start();
  }
  function stopRecord() {
    /**
    *   mediaRecorder.state返回当前状态 (闲置中,录制中或者暂停 ) (inactive, recording, or paused.)
    */
    if (mediaRecorder.state === "recording") {
      mediaRecorder.stop();
    }
  }
  function destroyRecord() {
    // 终止流(这可以让浏览器上正在录音的标志消失掉)
    stream.getTracks().forEach(track => track.stop());
    stream = null;
  }
  function pauseRecord() {
    mediaRecorder.pause();
  }
  function resumeRecord() {
    mediaRecorder.resume();
  }

  var ss = { fontSize: '20px', margin: '10px' }
  return (
    

文件大小:{fileSize}

); }

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