[英]getUserMedia() - selecting rear camera on mobile
This is my question. 这是我的问题。
I'm making a little app that uses JS-OCR to take a photo and detect a word. 我正在制作一个使用JS-OCR拍照和检测单词的小应用程序。 It works well, but in I only can user the front camera.
它运作良好,但是我只能使用前置摄像头。 My idea is to use only the rear camera, it's not necessary to have an option to switch the cameras.
我的想法是仅使用后置摄像头,没有必要选择切换摄像头。
I was reading about the getUserMedia()
function, but I can't solve the problem. 我正在阅读有关
getUserMedia()
函数的信息,但无法解决问题。 This is the piece of code involved (function searchForRearCamera()
): 这是所涉及的代码(函数
searchForRearCamera()
):
function searchForRearCamera() {
var deferred = new $.Deferred();
// Check that the browser supports getUserMedia.
// If it doesn't show an alert, otherwise continue.
if (navigator.getUserMedia) {
// Request the camera.
navigator.getUserMedia(
// Constraints
{
video: true
},
// Success Callback
function (localMediaStream) {
},
// Error Callback
function (err) {
// Log the error to the console.
console.log('The following error occurred when trying to use getUserMedia: ' + err);
}
);
} else {
alert('Sorry, your browser does not support getUserMedia');
}
//MediaStreamTrack.getSources seams to be supported only by Chrome
if (MediaStreamTrack && MediaStreamTrack.getSources) {
MediaStreamTrack.getSources(function (sources) {
var rearCameraIds = sources.filter(function (source) {
return (source.kind === 'video' && source.facing === 'environment');
}).map(function (source) {
return source.id;
});
if (rearCameraIds.length) {
deferred.resolve(rearCameraIds[0]);
} else {
deferred.resolve(null);
}
});
} else {
deferred.resolve(null);
}
return deferred.promise();
}
navigator.getUserMedia
is long deprecated. navigator.getUserMedia
早已被弃用。 Use navigator.mediaDevices.getUserMedia now. 立即使用navigator.mediaDevices.getUserMedia 。
To get the rear camera, you can use the MediaConstraint:video:facingMode property. 要获取后置摄像头,可以使用MediaConstraint:video:facingMode属性。 Available values are
'user'
(front camera), and 'environment'
(back camera). 可用值为
'user'
(前置摄像头)和'environment'
(后置摄像头)。
navigator.mediaDevices.getUserMedia({ audio: false, video: { facingMode: 'environment' } }) .then(stream => vid.srcObject = stream) .catch(console.error);
<video muted autoplay id="vid"></video>
Or as a fiddle since null origin StackSnippet's iframe may block the request to gUM. 或作为一个小玩意,因为null来源的StackSnippet的iframe可能会阻止对gUM的请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.