DOMException:play()只能由用户手势启动

时间:2016-08-05 14:32:05

标签: javascript android

我正在使用JavaScript处理QRCode Reader。 如果用户在我的Wensite上,则会要求获得使用相机的权限。一旦用户接受它,它就会打开frant camara。我使用三星Galaxy S4和最新的Chrome版本,到目前为止一切正常。

我已经从前面到下面的camara添加了一个Dropdown to Change。 一旦我更换相机,视频流就会停止,我收到此错误。

  

Uncaught(在promise中)DOMException:play()只能由a启动   用户手势。

我已经在较旧版本的Chrome上尝试过这种版本,即使是变革也很好。

            var videoElement = document.createElement("video");
            var videoSelect = document.querySelector("select#videoSource");

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

            function start() {
              if (window.stream) {
                videoElement.src = null;
                window.stream.stop();
              }
              var videoSource = videoSelect.value;
              var tw = 640 // 320 // 640 // 1280;
              var th = 480 // 240 // 480 // 720

              var hdConstraints = {
                audio: false,
                video: {
                    mandatory: {
                            maxWidth: tw,
                            maxHeight: th
                        },
                    optional: [{
                        sourceId: videoSource
                    }]
                }
              };
              if (navigator.getUserMedia) {
                navigator.getUserMedia(hdConstraints, success, errorCallback);
              } else {
                    errorCallback("");
                }
            }

            videoSelect.onchange = start;
            start();

            function gotSources(sourceInfos) {
              for (var i = 0; i !== sourceInfos.length; ++i) {
                var sourceInfo = sourceInfos[i];
                var option = document.createElement("option");
                option.value = sourceInfo.id;

                if (sourceInfo.kind === "video") {
                  option.text = sourceInfo.label || "camera " + (videoSelect.length + 1);
                  videoSelect.appendChild(option);
                } else {
                  console.log("Some other kind of source: ", sourceInfo);
                }

              }
            }

            if (typeof MediaStreamTrack === "undefined") {
              alert("This browser does not support MediaStreamTrack.\n\nTry Chrome.");
            } else {
              MediaStreamTrack.getSources(gotSources);
            }

            function errorCallback(e) {
                console.log("Cant access user media", e);
            }

            function success(stream) {

                window.stream = stream;
                videoElement.src = window.URL.createObjectURL(stream);
                videoElement.onclick = function() { videoElement.play(); };
                videoElement.play(); //Here is the Error


                function getFrame() {
                    requestAnimationFrame(getFrame);

                    if (!videoElement.videoWidth) return;

                    if (!image) {
                        width = videoElement.videoWidth, height = videoElement.videoHeight;
                        log("videoElement", width, height, videoElement);

                        var canvas = document.createElement("canvas");
                        canvas.width = width;
                        canvas.height = height;
                        canvas.style.transform = "scale(1, 1)";

                        ctx = canvas.getContext("2d");
                        document.body.appendChild(canvas);

                        log("start");
                        image = Module._xsetup(width, height);
                        log("_xsetup", image, "pointer");
                        return;
                    }

                    ctx.drawImage(videoElement, 0, 0, width, height);
                    var imageData = ctx.getImageData(0,0, width, height);
                    data = imageData.data;
                    gofill();
                }

                getFrame();

}

4 个答案:

答案 0 :(得分:13)

这可能与受信任的安全模型有关。某些操作仅在用户启动时才允许。这就是很多弹出窗口阻止程序的工作原理。同样,Chrome可能希望保护用户免受自动播放视频的影响。

确保在与手势相关联的事件处理程序中调用videoElement.play()

// this should be ok
videoElement.addEventListener("click", function () {
    videoElement.play();
});

// this is not ok
setTimeout(function () {
    videoElement.play();
});

由于在navigator.getUserMedia中调用了您的函数,再次请求用户输入似乎很奇怪。您是否尝试在autoplay元素上使用video

答案 1 :(得分:3)

所有拥有并试图解决此自动播放问题的人;它可能有点迟了但我在做了一些实验后想出了如何解决这个问题。我试图创建一个无限循环的声音,它在播放按钮后开始,我不想要它的HTML autoplay属性,它在重复时创建了间隙。然后我发现,如果我使用相同的声音<audio>创建一个src标签,然后我可以setTimeout(function);在第一个结束后开始第二个,这将是一个环。这是我面对这个play() DOMException的地方。在桌面上它是完美无瑕的,但在移动设备上,它正在停止,因为它需要一个手势。然后我发现,如果你用手势play()音频1次,那么你可以pause()设置currentTime = 0;然后再play()而无需用户手势。下面的代码为移动和桌面创建了无限循环,没有任何问题。

以下是 DEMO

<强> HTML

<audio id="rain" src="https://www.soundjay.com/nature/sounds/water-dripping-1.mp3" preload="auto">
</audio>
<audio id="rainloop" src="https://www.soundjay.com/nature/sounds/water-dripping-1.mp3" preload="auto">
</audio>
<button>
  Rain
</button>
<div id="slider"></div>

<强> JS

$(document).ready(function(){
  var interloop;
  var aud = document.getElementById("rain");
  var audloop = document.getElementById('rainloop');
  var wplay = aud;
  $('button').click(function(){
    if(aud.paused && audloop.paused){
      audloop.play();
      audloop.pause()
      audloop.currentTime = 0;
      looper();
    } else {
      aud.pause();
      aud.currentTime = 0;
      audloop.pause();
      audloop.currentTime = 0;
      clearInterval(interloop);
    }
  });

  function looper(){
        wplay.play();
        if(wplay == aud){
        wplay = audloop;
        } else {
        wplay = aud;
        }
    interloop = setTimeout(looper, 4600);
      }

  $('#slider').slider({
    value: 100,
    slide:changevolume,
    stop:changevolume
    });

  function changevolume(){
    var val = $('#slider').slider('value');
    aud.volume = (val/100);
    audloop.volume = (val/100);
  }
});

答案 2 :(得分:2)

我找到了一个更简单的解决方案。

<button #notificationSound (click)=" _notifService.initAudio()" hidden></button>
initAudio() {
    const audio = new Audio('./../assets/audio/notification.mp3');
    audio.muted = true
    audio.play();
}

初始化之后,您应该会很好。您也可以将其附加到鼠标悬停在身体​​上,这将算作手势。

答案 3 :(得分:1)

这可能有帮助。

webSettings.setMediaPlaybackRequiresUserGesture(false)