h5实现主播端推流

2021/2/7 2:30:33代码块js
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <title>测试摄像头</title>
  <style>
      html, body, video, body > div.video {
          height: 100%;
          width: 100%;
      }

      body {
          margin: 0;
          position: relative;
      }

      video {
          display: block;
      }

      body > div.video {
          position: absolute;
          left: 0;
          top: 0;
          right: 0;
          bottom: 0;
          z-index: 1;
          display: none;
          align-items: center;
          justify-content: center;
          flex-direction: column;
      }

      .video.show {
          display: flex;
      }
  </style>
</head>

<body>
<video src="" muted></video>
<div class="video"></div>
<script>
  let video = document.querySelector('video')
  let div = document.querySelector('div')
  const cameraErrorList = {
    AbortError: '由于长时间未操作,已终止',
    NotAllowedError: '已被拒绝打开摄像头',
    NotFoundError: '找不到摄像设备',
    NotReadableError: '无法读取摄像头',
    OverconstrainedError: '摄像头无法满足要求',
    SecurityError: '摄像头获取时,提示安全错误',
    TypeError: '摄像头类型错误',
  };
  navigator.mediaDevices.getUserMedia({
    audio: true,
    video: {
      // facingMode: 'user',//前置摄像头
      // facingMode: { exact: 'environment' },//后置摄像头
      // width: { ideal: 1280},
      // height: { ideal: 720 }
    }
  }).then(stream => {
    video.srcObject = stream
    video.onloadedmetadata = () => {
      video.play()
    }

    let mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.ondataavailable = function (enent) {
      let xhr = new XMLHttpRequest()
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            console.log('视频上传成功')
          }
        }
      }
      xhr.open('POST', '/', false)
      xhr.send(enent.data)
    }
    mediaRecorder.start(1000)
  })
  .catch(e => {
    div.innerText = cameraErrorList[e.name] || e.name || e.message
    div.classList.add('show')
  })
</script>
</body>

</html>