(一)通过浏览器访问摄像头

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<html>
<head>
<title>WebRTC capture video and audio</title>
<link rel="stylesheet" href="./css/client.css"/>
</head>

<body>

<video autoplay playsinline id="player"></video>

<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script src="./js/client.js"></script>
</body>
</html>

client.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
'use strict'

var videoplay = document.querySelector('video#player');

const mediaStreamContrains = {
video: {
frameRate: { min: 20 },
width: { min: 640, ideal: 1280 },
height: { min: 360, ideal: 720 },
aspectRatio: 16 / 9,
facingMode: 'user',
resizeMode: true
},
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
}
};

function gotMediaStream(stream) {
window.stream = stream;
videoplay.srcObject = stream;
}

function handleError(err) {
console.log('getUserMedia error:', err);
}

function start() {
if (!navigator.mediaDevices ||
!navigator.mediaDevices.getUserMedia) {
console.log('getUserMedia is not supported!');
return;
} else {
navigator.mediaDevices.getUserMedia(mediaStreamContrains)
.then(gotMediaStream)
.catch(handleError);
}
}

start();

效果

使用浏览器打开index.html就可以在浏览器里面看到前置摄像头影像了