【问题标题】:How to enable audio sound effects in live chat or bot chat?如何在实时聊天或机器人聊天中启用音频音效?
【发布时间】:2018-07-09 20:37:09
【问题描述】:

早安..

在 Google Chrome 于 2018 年 4 月更新其自动播放政策以防止在没有用户交互的情况下播放音频和视频后,我如何启动音效以通知用户新消息?

我不想自动播放音频,我只想在每次用户从另一行收到新消息时播放音效。

这是我需要实现的简单的 sn-p 代码:

function sendMessage(msg, callback){
  setTimeout(function(){
    document.querySelector('audio').play();
    var msg_body = document.createElement('div');
    msg_body.innerText = msg;
    document.querySelector('#chat-body').appendChild(msg_body);
    if(callback) callback();
  },2e3);
}

sendMessage('Hello', function(){
  sendMessage('Good Morning', function(){
    sendMessage('What\'s Your Name ?');
  });
});
#chat-body > div{border-radius:10px;background-color:#EEE;margin:10px;padding:10px}
<div id='chat-body'></div>
<audio src='https://notificationsounds.com/notification-sounds/plucky-564/download/mp3'></audio>

播放功能可能在 stackoverflow.com 上正常工作,因为它的参与率很高,但在我的页面中,甚至在 Codepen.com 上,音频都无法播放并且控制台返回错误:

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. goo.gl/xX8pDD

【问题讨论】:

    标签: javascript jquery html google-chrome html5-audio


    【解决方案1】:

    让音频元素静音,并为用户制作一个取消静音按钮: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#audiovideo_elements

    <audio id="audio" muted>
    <button id="unmuteButton"></button>
    
    <script>
      unmuteButton.addEventListener('click', function() {
        audio.muted = false;
      });
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多