在AngularJs中路由更改后,HTML5相机不会关闭

asg*_*oth 6 javascript video html5 camera angularjs

我正在测试HTML5的视频功能.通过指令userMedia,我可以通过我的MacBook上的相机开启navigator.getUserMedia()(实际上通过适配器使其跨浏览器 - 至少是那些支持它的人).

但是当我改变我的时候$route,我不再看到自己了(欢呼),但是相机没有关闭(绿灯保持亮起).只刷新页面会重置所有内容(这是正常的).

我希望看到改变$location.path()就能解决问题:

        link: function(scope, elm, attrs, ctrl) {
            ...
            var path = $location.path();
            scope.$watch(function() {
                return $location.path();
            }, function(value) {
                if (value && value !== path) {
                    $log.info('Location changed, switching off camera');
                    webRTCAdapter.detachMediaStream(elm[0]);
                }
            }, true);
        }
Run Code Online (Sandbox Code Playgroud)

detachMediaStream(Chrome):

    webRTCAdapter.detachMediaStream = function(element) {
        console.log("Detaching media stream");
        element.pause();
        element.src = '';
        element.parentNode.removeChild(element);
    };
Run Code Online (Sandbox Code Playgroud)

HTML:

<video id="localVideo" width="100%" autoplay="autoplay" user-media="user-media"></video>
Run Code Online (Sandbox Code Playgroud)

detachMediaStream执行(我看到必要的登录console.log),但相机没有关闭.

不知道怎么解决这个问题?我应该以某种方式卸载元素吗?

asg*_*oth 10

我找到了问题的原因.在LocalMediaStream将其在相机开关上创建的,需要通过使用停止stop()功能.

LocalMediaStream将附加到视频元素时,必须保留对创建对象的引用:

 controller: function($element) {
            var self = this;
            self.onUserMediaSuccess = function(stream) {
                $log.info("User has granted access to local media.");
                webRTCAdapter.attachMediaStream($element[0], stream);

                // keep a reference
                self.localStream = stream;
            };
Run Code Online (Sandbox Code Playgroud)

当事件发生时,此LocalMediaStream参考必须添加到detachMediaStream功能中$destroy(谢谢你,Joseph Silber):

scope.$on('$destroy', function() {
   $log.info('Location changed, switching off camera');
   webRTCAdapter.detachMediaStream( elm[0], ctrl.localStream);
});
Run Code Online (Sandbox Code Playgroud)

LocalMediaStream对象上我需要执行该stop()函数:

    webRTCAdapter.detachMediaStream = function(element, stream) {
        console.log("Detaching media stream");
        element.pause();
        element.src = '';
        element.parentNode.removeChild(element);

        // stopping stream (camera, ...)
        stream.stop();
    };
Run Code Online (Sandbox Code Playgroud)