提问者:小点点

谷歌Chrome在播放音频时未捕获(promise)DomeException。play()方法[重复]


$scope.sound = function () {
    // $scope.totalQueueList -->response is saved in this variable

    if ($scope.totalQueueList) {
        var audio = new Audio();
        audio.src = 'rest/assets/images/beep.mp3';
        var playedPromise = audio.play();               
        if (playedPromise) {
            playedPromise.catch((e) => {
                console.log(e)
                if(e.name === 'NotAllowedError' || e.name === 'NotSupportedError') {
                    console.log(e.name);
                    audio.loop = true
                }
            }).then(() => {

            });
        }
    }
}

手动刷新chrome浏览器页面时,此代码不起作用。它给了我音频的例外。play()方法。对于没有浏览器页面刷新的正常流,它可以工作。请提供解决方案。


共1个答案

匿名用户

您必须等待浏览器加载声音资源。使用canPlayThrough方法在资源准备好播放时获得通知:

$scope.sound = function() {
  // $scope.totalQueueList -->response is saved in this variable

  if ($scope.totalQueueList) {
    var audio = new Audio();
    audio.src = 'rest/assets/images/beep.mp3';

    // when the sound has been loaded, execute your code
    audio.oncanplaythrough = (event) => {
      var playedPromise = audio.play();
      if (playedPromise) {
        playedPromise.catch((e) => {
          console.log(e)
          if (e.name === 'NotAllowedError' || e.name === 'NotSupportedError') {
            console.log(e.name);
            audio.loop = true
          }
        }).then(() => {

        });
      }
    }
  }
}