【问题标题】:Uncaught (in promise) DOMException when playing notification sound播放通知声音时未捕获(承诺)DOMException
【发布时间】:2019-11-28 01:11:54
【问题描述】:

我正在处理我的项目中的通知,当有新订单时通知用户。并且每 5 秒更新一次队列计数。

<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>

我试过这段代码 sn-p 仍然触发 DOMException 错误

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.
    });
}

有什么办法可以消除这个错误吗?

【问题讨论】:

标签: jquery laravel


【解决方案1】:

你可以尝试如下,

<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>

【讨论】:

  • 能否请您强调一下您在哪里得到 dom 引用错误?
  • 它现在可以工作了,但我现在的新问题是音频不会播放,除非我点击页面做某事。
猜你喜欢
  • 2019-07-10
  • 2019-11-03
  • 2020-05-14
  • 1970-01-01
  • 2019-05-27
  • 2017-05-16
  • 2017-04-03
  • 1970-01-01
  • 2019-07-22
相关资源
最近更新 更多