我正在处理我的项目的通知,当有新订单时通知用户。并每 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>
我尝试了这个代码片段,但仍然触发了 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.
});
}
有什么方法可以摆脱此错误吗?
你可以试试下面,
<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>