trackjs怎么关闭摄像头
最近开发一个谷歌浏览器扩展,有需要用到人脸识别,因此使用了trackjs来实现这个功能,但是一直遇到问题是在调用trackerTask.stop();停止识别后,摄像头依然无法关闭;
trackerTask是什么?
trackerTask = tracking.track(‘#face_video_video’, tracker, { camera: true });
网上寻找多久后终于找到如下解决办法
在trackingjs源码中找到以下代码 /** * Captures the user camera when tracking a video element and set its source * to the camera stream. * @param {HTMLVideoElement} element Canvas element to track. * @param {object} opt_options Optional configuration to the tracker. */ tracking.initUserMedia_ = function(element, opt_options) { window.navigator.mediaDevices.getUserMedia({ video: true, audio: (opt_options && opt_options.audio) ? true : false, }).then(function(stream) { element.srcObject = stream; window.stream = stream; //增加这一行,将元素的stream赋予到window }).catch(function(err) { throw Error('Cannot capture user camera.'); }); }; 然后找到以下代码,包含开启摄像头的方法 tracking.track = function(element, tracker, opt_options) { element = tracking.one(element); element.srcObject = window.stream; //加上这行 if (!element) { throw new Error('Element not found, try a different element or selector.'); } if (!tracker) { throw new Error('Tracker not specified, try `tracking.track(element, new tracking.FaceTracker())`.'); } switch (element.nodeName.toLowerCase()) { case 'canvas': return this.trackCanvas_(element, tracker, opt_options); case 'img': return this.trackImg_(element, tracker, opt_options); case 'video': if (opt_options) { if (opt_options.camera) { this.initUserMedia_(element, opt_options); } } return this.trackVideo_(element, tracker, opt_options); default: throw new Error('Element not supported, try in a canvas, img, or video.'); } };
然后关闭
if (typeof window.stream === "object") { //关闭摄像头 window.stream.getTracks().forEach(track => track.stop()); document.getElementById("xxx").srcObject = null; }
xxx就是初始化track时候配置的video元素
但是,调用摄像头指示灯是关闭了,但在地址栏依然能看到当前网页正在使用,不知道究竟是关闭了还是没有关闭处于静默状态
快捷登陆