我正在研究 QRCode Reader
和 JavaScript
。如果用户在我的网站上,它会请求使用设备相机的权限。一旦用户接受它,它就会打开前置摄像头。我使用的是三星 Galaxy S4 和最新的 Chrome 版本,目前运行良好。
我添加了一个下拉菜单以从前摄像头更改为后摄像头。一旦我更换相机,视频流就会停止,并且出现此错误。
未捕获(承诺)DOMException:play() 只能由用户手势启动。
我已经在较旧版本的 Chrome 上尝试过它,即使是 camare 更改也能正常工作。
var videoElement = document.createElement("video");
var videoSelect = document.querySelector("select#videoSource");
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
function start() {
if (window.stream) {
videoElement.src = null;
window.stream.stop();
}
var videoSource = videoSelect.value;
var tw = 640 // 320 // 640 // 1280;
var th = 480 // 240 // 480 // 720
var hdConstraints = {
audio: false,
video: {
mandatory: {
maxWidth: tw,
maxHeight: th
},
optional: [{
sourceId: videoSource
}]
}
};
if (navigator.getUserMedia) {
navigator.getUserMedia(hdConstraints, success, errorCallback);
} else {
errorCallback("");
}
}
videoSelect.onchange = start;
start();
function gotSources(sourceInfos) {
for (var i = 0; i !== sourceInfos.length; ++i) {
var sourceInfo = sourceInfos[i];
var option = document.createElement("option");
option.value = sourceInfo.id;
if (sourceInfo.kind === "video") {
option.text = sourceInfo.label || "camera " + (videoSelect.length + 1);
videoSelect.appendChild(option);
} else {
console.log("Some other kind of source: ", sourceInfo);
}
}
}
if (typeof MediaStreamTrack === "undefined") {
alert("This browser does not support MediaStreamTrack.\n\nTry Chrome.");
} else {
MediaStreamTrack.getSources(gotSources);
}
function errorCallback(e) {
console.log("Cant access user media", e);
}
function success(stream) {
window.stream = stream;
videoElement.src = window.URL.createObjectURL(stream);
videoElement.onclick = function() { videoElement.play(); };
videoElement.play(); //Here is the Error
function getFrame() {
requestAnimationFrame(getFrame);
if (!videoElement.videoWidth) return;
if (!image) {
width = videoElement.videoWidth, height = videoElement.videoHeight;
log("videoElement", width, height, videoElement);
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.style.transform = "scale(1, 1)";
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
log("start");
image = Module._xsetup(width, height);
log("_xsetup", image, "pointer");
return;
}
ctx.drawImage(videoElement, 0, 0, width, height);
var imageData = ctx.getImageData(0,0, width, height);
data = imageData.data;
gofill();
}
getFrame();
}
原文由 Mihawk 发布,翻译遵循 CC BY-SA 4.0 许可协议
这可能与受信任的安全模型有关。某些操作只有在用户启动时才被允许。例如,许多弹出窗口拦截器就是这样工作的。同样,Chrome 可能希望保护用户免受自动播放视频的影响。
确保在与手势关联的事件处理程序中调用
videoElement.play()
。由于您的函数是在
navigator.getUserMedia
中调用的,因此再次要求用户输入似乎很奇怪。您是否尝试过在autoplay
元素上使用video
?