webRTC学习-同时打开麦克风和摄像头案例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>打开摄像头</title>
</head>
<body>
<!--添加muted后,就无法捕获到麦克风的声音-->
<!--<video id="local-video" autoplay playsinline muted></video>-->
<!--controls:是否显示控件-->
<video id="local-video" autoplay playsinline controls></video>
<button id="showVideo">打开摄像头+麦克风</button>
<p>通过getUserMedia()获取视频+麦克风</p>

</body>
<script type="text/javascript">
  document.querySelector('#showVideo').addEventListener('click', onOpenCamera);
  //约束条件
  const constraints = {
    
    
    audio: true,
    video: true
  }
  //打开摄像头成功的处理
  const handleSuccess = (stream => {
    
    
    //处理打开摄像头成功
    //获取video组件
    const video = document.querySelector("#local-video")
    video.srcObject = stream
  })
  //    异常处理
  const handleError = (err => {
    
    
    console.error("getUserMedia error:" + err)
  })

  //点击按钮打开摄像头
  function onOpenCamera(e) {
    
    
    navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess).catch(handleError)
  }
</script>
</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/fangqi20170515/article/details/129181639