【问题标题】:How to autoplay audio when the countdown timer is finished?倒数计时器完成后如何自动播放音频?
【发布时间】:2019-04-03 16:46:12
【问题描述】:

我想在倒计时结束后播放声音。 通常我会使用这种和平的代码来做到这一点

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

但是我得到以下错误Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context,可能是因为用户拒绝了权限。

事情是......谷歌它自己正在使用 HTML5 音频标签来做这件事

如果您在谷歌搜索字段中输入countdown timer,它应该会显示在倒计时结束后播放声音的小部件。

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

【问题讨论】:

    标签: javascript html5-audio


    【解决方案1】:

    通过让您单击此“开始”按钮,他们要求用户做出手势,从而将他们的文档标记为用户已批准播放音频。这意味着它们不再受 chrome 的 autoplay policies 约束。

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

    所以在你的情况下,它不会起作用,即使你确实从像谷歌这样的点击开始倒计时。

    然后解决方案是从点击事件开始播放,然后立即暂停。这样做,您的元素将被标记为用户已批准,您将完全控制它。

    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>

    【讨论】:

    • 像魅力一样工作!谢谢队友:)
    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 2018-03-21
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多