0

Im working with notifications on my project which notify users when there are new orders. And update queue count every 5 seconds.

<audio id="foobar" src="{{URL::to('/')}}/assets/notif_sounds/plucky.mp3" preload="auto" autoplay="false"> 

 <script>
     setInterval(function(){ 
        $.ajax({
          type:'POST',
          url:'{{URL::to('/')}}/get-count',
          success:function(data)
          {    
            $('#qCount').html(data);
            var sample = document.getElementById("foobar");
            sample.play();
           }
        });
     }, 5000);  
   </script>

I tried this code snippet and still fire DOMException error

var promise = document.querySelector('audio').play();

if (promise !== undefined) {
    promise.then(_ => {
        // Autoplay started!
    }).catch(error => {
        // Autoplay was prevented.
        // Show a "Play" button so that user can start playback.
    });
}

Is there any way how to get rid of this error?

Franz
  • 354
  • 1
  • 4
  • 15
  • 1
    Possible duplicate of [How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()](https://stackoverflow.com/questions/40276718/how-to-handle-uncaught-in-promise-domexception-the-play-request-was-interru) – 4b0 Jul 19 '19 at 04:53
  • I already tried the answer given on that question but still i get the DOMException error. – Franz Jul 19 '19 at 05:00

1 Answers1

0

You can try as below,

<script>
     // Create Audio object.
     var audio = new Audio('{{URL::to('/')}}/assets/notif_sounds/plucky.mp3');

     setInterval(function(){ 
        $.ajax({
          type:'POST',
          url:'{{URL::to('/')}}/get-count',
          success:function(data)
          {    
            $('#qCount').html(data);
            var sample = document.getElementById("foobar");

            // Play whenever you want.
            audio.play();
           }
        });
     }, 5000);  
   </script>
Vaibhavraj Roham
  • 1,138
  • 11
  • 26