【发布时间】:2019-07-22 10:20:17
【问题描述】:
我正在尝试使用 WebRTC 访问移动摄像头。我已经根据我在网上找到的内容进行了设置。但是,我遇到了一些问题。
- 我的代码似乎无法在 Android 设备上运行。
- 当我尝试设置视频的
width和height属性时,它不起作用。 - 在 iOS 上观看视频时。然后离开 Safari 应用程序几秒钟。然后返回到视频两侧为黑色/更改纵横比的页面?
有人知道如何解决这些问题/有更好的实现吗?
插图
我的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<video id="video"></video>
<script type="text/javascript">
var video; // INPUT WEBRTC as <video> tag
var cameras = ["user", "environment"]; // USUAL CAMERA TYPES
var options = []; // CAMERAS AVAILABLE
navigator.mediaDevices.enumerateDevices().then((devices) => {
let index = 0;
devices.find((device) => {
if (device.kind === 'videoinput') {
if (device.deviceId == '') {
options.push({
audio: false,
video: {
facingMode: {
exact: cameras[index]
}
}
});
index++;
} else {
options.push({
audio: false,
video: {
deviceId: {
exact: device.deviceId
}
}
});
}
}
});
if (options.length == 0) {
console.log("NO DEVICES FOUND");
} else {
navigator.mediaDevices.getUserMedia(options[options.length - 1]).then(stream => {
video = document.getElementById("video");
video.setAttribute('playsinline', 'playsinline');
video.setAttribute('position', 'absolute');
video.setAttribute('top', '0');
video.setAttribute('left', '0');
document.body.appendChild(video);
try {
video.srcObject = stream;
video.style.display = 'block';
video.play();
} catch (error) {
video.src = URL.createObjectURL(stream);
video.style.display = 'block';
video.play();
}
// TRYING TO CHANGE VIDEO SIZE BELOW DOESN'T WORK
/*
var w = window.innerWidth;
var h = w * (video.videoHeight / video.videoWidth);
video.width = w;
video.height = h;
*/
})
}
}).catch(err => {
console.log(err);
});
</script>
</body>
</html>
【问题讨论】:
-
解决这个问题的一个简单方法是在视频容器中使用 CSS 的
object-fit属性。
标签: javascript html webrtc