倒数计时器结束后如何自动播放音频? [英] How to autoplay audio when the countdown timer is finished?

查看:315
本文介绍了倒数计时器结束后如何自动播放音频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在倒数计时器完成后播放声音. 通常我会使用这种和平的代码来做到这一点

I want to play a sound after the countdown timer is done. Normally I will do it using this peace of code

   var audio = new Audio('path to file.mp3');
   audio.play();

但是我收到以下错误未处理的承诺拒绝:NotAllowedError:在当前上下文中,用户代理或平台不允许该请求,可能是因为用户拒绝了权限.

问题是... Google自己使用HTML5音频标签来实现

The thing is ... Google it self is doing it using a HTML5 audio tag

如果您在Google搜索字段中键入countdown timer,它应该向您显示在倒数计时器结束后播放声音的小部件.

If you type countdown timer into google search field it should show you the widget that plays a sound after the countdown timer is finished.

如果你们不知道我在说什么,这就是Google计时器的样子:)

Here is how Googles timer look like, if you guys don't know what I'm talking about :)

推荐答案

通过使您单击此开始"按钮,他们要求用户做出手势,因此已将其文档标记为被用户批准播放音频.这表示它们不受chrome的自动播放政策的约束不再.

By making you click this "START" button, they ask for an user gesture and thus have marked their document as approved-by-user to play audio. This means they are not subject for chrome's autoplay policies anymore.

现在,默认情况下,Safari的浏览器甚至比Chrome更严格,并且单击文档不起作用:在此浏览器中,您需要从用户事件本身开始播放.

Now, Safari by default is even stricter than Chrome here, and a simple click on the document doesn't work: in this browser you need to start the playback from the user-event itself.

因此,就您而言,即使您确实是通过Google之类的点击开始倒计时的,它也不会起作用.

So in your case, it won't work, even if you did start the countdown from a click like Google.

然后的解决方案是从click事件开始播放,然后立即暂停播放.这样做,您的元素将被标记为已被用户批准,您将对其拥有完全控制权.

The solution is then to start the playback from the click event, and to pause it immediately after. Doing so, your Element will be marked as approved-by-user and you will ave full control over it.

const audio = new Audio("https://dl.dropboxusercontent.com/s/1cdwpm3gca9mlo0/kick.mp3");
let time = 5;

btn.onclick = e => {
  // mark our audio element as approved by the user
  audio.play().then(() => { // pause directly
    audio.pause();
    audio.currentTime = 0;
  });
  countdown();
  btn.disabled = true;
};


function countdown() {
  pre.textContent = --time;
  if(time === 0) return onend();
  setTimeout(countdown, 1000);
}


function onend() {
  audio.play(); // now we're safe to play it
  time = 5;
  btn.disabled = false;
}

<button id="btn">start countdown</button><br>
<pre id="pre"></pre>

这篇关于倒数计时器结束后如何自动播放音频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆