-1
$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(() => {

            });
        }
    }
}

This code is not working when doing a manual page refresh of the chrome browser. It gives DOMException for audio.play() method. For normal flow without a browser page refresh, it works. Please provide a solution.

nopassport1
  • 1,821
  • 1
  • 25
  • 53

1 Answers1

0

You have to wait until the sound resource has been loaded by your browser. Use the method canPlayThrough to get informed when the resource is ready to be played:

$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(() => {

        });
      }
    }
  }
}
SparkFountain
  • 2,110
  • 15
  • 35