webrtc打开默认摄像头

1.main.js

核心代码:

 const stream = await navigator.mediaDevices.getUserMedia(constraints);
/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */
'use strict';

// Put variables in global scope to make them available to the browser console.
const constraints = window.constraints = {
  audio: false,
  video: true
};

function handleSuccess(stream) {
  const video = document.querySelector('video');
  const videoTracks = stream.getVideoTracks();
  console.log('Got stream with constraints:', constraints);
  console.log(`Using video device: ${videoTracks[0].label}`);
  //window.stream = stream; // make variable available to browser console
  video.srcObject = stream;
}

function handleError(error) {
  if (error.name === 'ConstraintNotSatisfiedError') {
    let v = constraints.video;
    errorMsg(`The resolution ${v.width.exact}x${v.height.exact} px is not supported by your device.`);
  } else if (error.name === 'PermissionDeniedError') {
    errorMsg('Permissions have not been granted to use your camera and ' +
      'microphone, you need to allow the page access to your devices in ' +
      'order for the demo to work.');
  }
  errorMsg(`getUserMedia error: ${error.name}`, error);
}

function errorMsg(msg, error) {
  const errorElement = document.querySelector('#errorMsg');
  errorElement.innerHTML += `

${msg}

`; if (typeof error !== 'undefined') { console.error(error); } } async function init(e) { try { const stream = await navigator.mediaDevices.getUserMedia(constraints); handleSuccess(stream); e.target.disabled = true; } catch (e) { handleError(e); } } document.querySelector('#showVideo').addEventListener('click', e => init(e));

2.index.html






    
    
    
    
    
    
    
    

    

    getUserMedia

    
    
    





WebRTC samples getUserMedia

Warning: if you're not using headphones, pressing play will cause feedback.

Display the video stream from getUserMedia() in a video element.

The MediaStream object stream passed to the getUserMedia() callback is in global scope, so you can inspect it from the console.

View source on GitHub

 

你可能感兴趣的:(WebRTC流媒体技术)