如何在实时聊天或机器人聊天中启用音频音效?

How to enable audio sound effects in live chat or bot chat?

早上好..

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

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

这是我的代码片段,简单说明了我需要实现的目标:

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>

播放功能可能在 whosebug.com 上正常运行,因为它的参与率很高,但在我的页面甚至 Codepen.com 音频无法播放和控制台 returns 错误:

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

让音频元素静音,并为用户制作一个取消静音按钮: 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>