Search code examples
ionic-frameworkgetusermedia

Use getUserMedia with ionic get only black screen


Im testing some media features with ionic and im stuck while trying to set the camera output into a video tag using getUserMedia using this code:

navigator.getUserMedia = navigator.getUserMedia ||
                     navigator.webkitGetUserMedia ||
                     navigator.mozGetUserMedia;

if (navigator.getUserMedia) {
   navigator.getUserMedia({ audio: false, video: { width: 500, height: 500 } },
      function(stream) {
         console.log("Im streaming!!", stream);
         var video = document.querySelector('video');
         console.log("video element", video);
         video.src = window.URL.createObjectURL(stream);
         video.onloadedmetadata = function(e) {
            console.log("stream start");
            video.play();
         };
      },
      function(err) {
         console.log("The following error occurred: " + err.name);
      }
   );
} else {
   console.log("getUserMedia not supported");
}

this is the html:

    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Ionic Blank Starter</h1>
      </ion-header-bar>
      <ion-content>
        <video  id="video" autoplay="autoplay" width="500" height="500"></video>
      </ion-content>
    </ion-pane>

i can actually get only a black screen. Is my approach right or im missing something?


Solution

  • The final solution to this problem is that getUserMedia require a runtime permission check to work. To achieve that i used this plugin. Then this worked like a charm:

    cordova.plugins.diagnostic.requestRuntimePermission(function(status){
        if(cordova.plugins.diagnostic.runtimePermissionStatus.GRANTED){
          navigator.getUserMedia({video: true, audio: false}, function(localMediaStream) {
            var video = document.querySelector('video');
            video.src = window.URL.createObjectURL(localMediaStream);
    
            video.onloadedmetadata = function(e) {
              console.log('Stream is on!!', e);
            };
          }, errorCallback);
        }
    
    });