播放audio.play()方法时未捕获Google Chrome(承诺)DOMException

时间:2020-01-29 13:13:11

标签: javascript angularjs

$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浏览器时,此代码不起作用。它为audio.play()方法提供DOMException。 对于没有刷新浏览器页面的正常流程,它可以工作。请提供解决方案。

1 个答案:

答案 0 :(得分:0)

您必须等待,直到浏览器加载了声音资源。使用canPlayThrough方法来获取何时可以播放资源的通知:

12-2019