How to autoplay audio when the countdown timer is finished?

帅比萌擦擦* 提交于 2020-06-28 08:33:51

问题


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();

But I get the following error Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

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

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.

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

google widget


回答1:


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.

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.

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

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>


来源:https://stackoverflow.com/questions/55490155/how-to-autoplay-audio-when-the-countdown-timer-is-finished

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!