代码之家  ›  专栏  ›  技术社区  ›  Muhammad Saleh

如何在实时聊天或bot聊天中启用音频声音效果?

  •  0
  • Muhammad Saleh  · 技术社区  · 6 年前

    早上好。。

    在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>

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

    Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. goo.gl/xX8pDD
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Muhammad Saleh    6 年前

    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>