如何在 Chrome 上请求用户对音频的许可?

How can I request user permission for audio on Chrome?

我正在研究 SAAS 解决方案,我需要客户从应用程序接收通知声音。即使他们只是在没有与它进行任何交互的情况下启动它。 Google 已更改 Chrome 这方面的行为,现在用户需要单击网页才能获得通知声音。我发现可以在此处明确允许声音:

然后用户应该为您的网站明确启用声音:

现在用户无需单击即可启用声音通知。我的问题:是否可以像我们为麦克风那样请求用户对声音的许可:

只需制作您自己的警报模式即可。您可以通过在静音时尝试播放音频来检测是否需要它

const audio = new Audio( 'https://dl.dropboxusercontent.com/s/h8pvqqol3ovyle8/tom.mp3' );
audio.muted = true;

const alert_elem = document.querySelector( '.alert' );

audio.play().then( () => {
  // already allowed
  alert_elem.remove();
  resetAudio();
} )
.catch( () => {
  // need user interaction
  alert_elem.addEventListener( 'click', ({ target }) => {
    if( target.matches('button') ) {
      const allowed = target.value === "1";
      if( allowed ) {
        audio.play()
          .then( resetAudio );
      }
      alert_elem.remove();
    }
  } );
} );

document.getElementById( 'btn' ).addEventListener( 'click', (e) => {
  if( audio.muted ) {
    console.log( 'silent notification' );
  }
  else {
    audio.play();
  }
} );

function resetAudio() {
  audio.pause();
  audio.currentTime = 0;
  audio.muted = false;
}
.alert {
  font: 14px Arial, sans-serif;
  position: fixed;
  top: 0;
  left: 0;
  background: white;
  border: 1px solid lightgray;
  box-shadow: 3px 3px 12px lightgray;
}
p { margin: 12px; }
.alert .buttons {
  float: right
}
<div class="alert">
  <p>This webpage would like to play sounds</p>
  <p class="buttons">
    <button value="0">Block</button>
    <button value="1">Allow</button>
  </p>
</div>
<button id="btn">trigger notification</button>


Ps:如果您对这个尚未实现的功能感兴趣,请注意 Permissions API specs, but this one is for allowing devices through HTMLMediaElement.setSinkId() method, which is yet another beast. (you can see this Q/A 中有一个 "speaker" 值。