Search code examples
angularjsangular-ui-routervideo-streamingrtsphls.js

destroy hls.js stream after ui-router state change


in my app I use video stream. I call this stream from my API and with video tag display streams in angularjs app.

<video id="video" class="iframePreview" controls="true" autoplay
       type="application/x-mpegURL">
</video>
<button class="button_pv btn btn-default"
        ui-sref="camera({'streamID': monitorsIds[0] })">
   Recorded Events
</button>

and in ctrl, I take URL from API and pass to <video></video

return $http
    .get(serviceBase + "aaaaaa" + Id)
    .then(function(response) {
      $rootScope.monitorsIds = [];

      angular.forEach(response.data, function(key, value) {
        $rootScope.monitorsIds.push(key.monitor);
      });
    if(Hls.isSupported()) {

        var video = document.getElementById('video');
        var hls = new Hls();
        hls.loadSource(window.monitorsIdsStreamWin[0]);
        hls.attachMedia(video);
    }
    });

Everything is working nice, but when I change state in my network console I still see loading stream data...

How to destroy this? Thnx


Solution

  • Here is a general purpose directive:

    app.directive("hlsSource", function() {
        return {
            link: postLink,
        };
        function postLink(scope, elem, attrs) {
            var hls;
            var video = elem[0];
            scope.$watch(attrs.hlsSource, function(value) {
                if (!value) return;
                //else
                hls && hls.destroy();
                hls = new Hls();
                hls.loadSource(value);
                hls.attachMedia(video);
                scope.$eval(attrs.onAttach({$hls: hls, $video: video});
            });
            scope.$onDestroy(function() {
                hls && hls.destroy();                
            });
        }
    });
    

    Usage:

    <video id="video" class="iframePreview" controls="true" autoplay
           type="application/x-mpegURL"
           hls-source="$ctrl.source" on-attach="$ctrl.onAttach($hls,$video)">
    </video>
    

    JS

    app.controller("videoController", function() {
        var current_hls;
        var current_video;
        this.onAttach = function(hls, video) {
            current_hls = hls;
            current_video = video;
            hls.on(Hls.Events.MANIFEST_PARSED,function() {
               current_video.play();
            });
        };
        this.$onDestroy = function() {
            current_hls && current_hls.destroy();
        };
        this.source = 'https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8';
    })