如何请求用户对Chrome上的音频的许可? [英] How can I request user permission for audio on Chrome?

查看:168
本文介绍了如何请求用户对Chrome上的音频的许可?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on SAAS solution and I need customers to receive notification sounds from the application. Even if they just launched it without any interaction with it. Google has changed Chrome behaviour regarding this aspect and now user is required to click on webpage to get notification sounds. I have found out that it is possible to allow sounds explicitly here:

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

and then user should enable sounds explicitly for your websites:

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

Now user will not have to click to enable sound notifications. My question: is it possible to request user permission for sound the same way we do it for microphone:

推荐答案

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

Simply make your own alert modal. You can feature detect if it is required or not by trying to play your audio while muted

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:请注意,权限API规范,但这是用于允许通过HTMLMediaElement.setSinkId()方法的设备,这是另一种野兽. (如果您有兴趣,可以参见此问题/答案尚未实现的功能).

Ps: note that there is a "speaker" value in Permissions API specs, but this one is for allowing devices through HTMLMediaElement.setSinkId() method, which yet an other beast. (you can see this Q/A if you are interested in this not yet implemented feature).

这篇关于如何请求用户对Chrome上的音频的许可?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆