如何在收到Web推送通知时播放自定义声音。

3

我实现了Web推送通知。虽然通知已经发送成功,但我想要播放我添加的自定义通知声音,而不是系统默认的窗口声音。我希望能够播放这个声音。我在代码中添加了一些内容以了解为什么无法播放这个通知声音。

self.addEventListener('push', async function (event) {
  const data = event.data.json();
  console.log(data);
  const title = 'Sound Notification';
  const options = {
    sound: '../public/messageNotification.mp3',
  };

  try {
      registration.showNotification(title, options);
  } catch (e) {
    registration.showNotification(title, options);
  }
});

我们可以使用 useRef 钩子并在接收事件后播放:myAudio.current.play()。 - Sonu Sindhu
3个回答

5

我认为您可以使用HTMLAudioElement来实现此目的。例如:

let sound: HTMLAudioElement;
sound = new Audio();
sound.src = '../public/messageNotification.mp3';
sound.load();
sound.play();

1

我们需要查看一下registration.showNotification的功能,但如果它正常工作而声音仍然没有播放,那可能是因为现代浏览器在某些情况下会阻止自动播放。

例如,Chrome有这个自动播放策略。Firefox和Safari可能有稍微不同的策略。

在这些情况下,您可能需要为每个浏览器找到解决方法,或者您可以指示用户始终为您的站点启用自动播放。在Chrome 104中,您可以通过单击锁定图标(位于URL旁边),选择网站设置,然后在声音下选择允许来实现此目的。

Click on the lock icon, then select Site settings

Select Allow under Sound


-1
const song = new Audio("url");
song.play(); // to play the audio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接