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

问题描述 投票:0回答:4

我实现了网络推送通知。通知即将到来,但我想播放我添加的自定义通知声音,但该声音不起作用默认系统窗口声音即将到来,我想播放此声音。我添加了代码,让我知道为什么这个通知声音没有播放接收

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);
  }
});
javascript reactjs push-notification
4个回答
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 旁边)、选择

Site settings
,然后在
Sound
下选择
Allow

来执行此操作


0
投票

你不能。浏览器接收网络推送通知。浏览器不允许自定义通知声音。


-1
投票
const song = new Audio("url");
song.play(); // to play the audio
© www.soinside.com 2019 - 2024. All rights reserved.