webrtc实现简单的移动摄像头调用
navigator.mediaDevices.getUserMedia()函数打开摄像头并输出流
videoEle.srcObject将流媒体数据输出到video中
代码:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>webRTC摄像头调用title>
<script src="https://libs.baidu.com/jquery/1.10.2/jquery.min.js">script>
<style>
#video {
width: 100%;
max-height: 500px;
background-color: black;
transform: rotateY(180deg); /*镜像翻转 解决前置摄像头镜像问题*/
}
#errorMsg {
background-color: chocolate;
margin-bottom: 4px;
}
#tipMsg {
background-color: cyan;
margin-bottom: 4px;
}
style>
head>
<body>
<div id="container">
画面:<br>
<video id="video" autoplay playsinline>video><br>
<p>
<button id="showVideo">打开前置摄像头button>
p>
<p>
<button id="stopVideo">关闭摄像头button>
p>
<p>点击打开摄像头按钮后,浏览器会询问是否允许,请点击“允许”。p>
<div id="tipMsg">div>
<div id="errorMsg">div>
div>
<script>
const constraints = window.constraints = {
audio: false,
video: {
// facingMode: 'environment', //后置摄像头
facingMode: 'user', //前置摄像头
},
};
function showErrMsg(msg, error) {
const errorElement = document.querySelector('#errorMsg');
errorElement.innerHTML += `<div>-> ${msg}</div>`;
if (typeof error !== 'undefined') {
console.error(error);
}
}
function showMsg(msg) {
const msgEle = document.querySelector('#tipMsg');
msgEle.innerHTML += `<div>-> ${msg}</div>`;
console.log(msg);
}
//打开摄像头
async function openCamera(e) {
try {
showMsg('正在打开摄像头');
const stream = await navigator.mediaDevices.getUserMedia(constraints);
showMsg('获取到了stream');
gotStream(stream);
e.target.disabled = true;
} catch (err) {
showErrMsg('没有摄像头设备')
}
}
//将视频流输出到video
function gotStream(stream) {
const videoEle = document.querySelector('#video');
const videoTracks = stream.getVideoTracks();
showMsg(`正在使用的设备: ${videoTracks[0].label}`);
window.stream = stream;
videoEle.srcObject = stream;
}
//停止视频流
function stopVideo(e) {
showMsg("停止视频");
const videoElem = document.querySelector('#video');
const stream = videoElem.srcObject;
document.querySelector('#showVideo').disabled = false; // 允许开启
if (stream == null) {
return;
}
const tracks = stream.getTracks();
tracks.forEach(function (track) {
track.stop();
});
videoElem.srcObject = null;
}
//点击打开前置摄像头
$('#showVideo').click((e) => {
openCamera(e)
})
//点击关闭摄像头
$('#stopVideo').click(e => {
stopVideo(e)
})
script>
body>
html>