使用Navigator.getUserMedia()作为承诺。?

时间:2016-08-12 10:51:11

标签: promise

我想将navigator.getUserMedia()实现为promise。

然后,当承诺得到解决后,我将执行一些成功的回调,并且在拒绝时我将执行失败回调。

1 个答案:

答案 0 :(得分:0)

试试这个:

function getUserMedia() {
  var constraints = {
    video: true, 
    audio: true
  };
  var deferred = jQuery.Deferred();
  if (location.protocol !== "https:") {
      alert('WARNING: Add https:// before the current url to capture video through WebCam');
      deferred.reject(false);
      return deferred.promise();
  } else {
    navigator.getUserMedia = navigator.getUserMedia ||
    navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia;

    if (navigator.getUserMedia) {
      navigator.getUserMedia(constraints, function(stream) {
        stream.stop = function() {
          this.getVideoTracks().forEach(function (track) {
            track.stop();
            track.enabled = !track.enabled;
          });
          this.getAudioTracks().forEach(function (track) {
            track.stop();
            track.enabled = !track.enabled;
          });
        };
        deferred.resolve(stream);
      }, function(err) {
        deferred.reject(err);
      });
      return deferred.promise();
    } else {
      console.log("getUserMedia not supported");
    }
  }