【问题标题】:How to play audio/sound in firebase-messaging-sw.js如何在 firebase-messaging-sw.js 中播放音频/声音
【发布时间】:2022-11-22 17:49:51
【问题描述】:

我遇到了关于如何在firebase-messaging-sw.js 中播放通知声音/音频文件的问题。但是消息发送成功。这是我到目前为止实施的

importScripts("https://gstatic.com/firebasejs/9.9.3/firebase-app-compat.js");
importScripts("https://gstatic.com/firebasejs/9.9.3/firebase-messaging-compat.js");

firebase.initializeApp({
  messagingSenderId: "...",
});
const messaging = firebase.messaging();

messaging.onBackgroundMessage(function (payload) {
  const options= {
    body: notification.body,
    icon: notification.icon,
    sound: "/media/notification.mp3",
  };

  return self.registration.showNotification(payload.notification.title, options);
});

从我从多个来源读到的内容来看,firebase 云消息传递仅在移动设备中提供声音通知。

但是,当通知出现在我的桌面/浏览器中时,我想播放音频/声音。有没有办法在浏览器中播放音频?

我也试过像这样播放音频

messaging.onBackgroundMessage(function (payload) {
  const options = {
    body: notification.body,
    icon: notification.icon,
    sound: "/media/notification.mp3",
  };

  const audio = new Audio("/media/notification.mp3");
  audio.play();

  return self.registration.showNotification(payload.notification.title, options);
});

但仍然无法播放音频通知。

这是请求 POST 到 FCM https://fcm.googleapis.com/fcm/send,带有正文参数

{
  "notification": {
    "title": "Title Notification",
    "body": "Lorem ipsum dolor",
    "click_action": "FCM_PLUGIN_ACTIVITY",
    "icon": "/media/logos/png-Icon-Logo.ico",
    "sound": "/media/notification.mp3"
  },
  "to": "...", // firebase messaging token
  "priority": "high"
}

通知工作没有问题,但通知显示时没有音频反馈。

【问题讨论】:

    标签: javascript firebase firebase-cloud-messaging service-worker


    【解决方案1】:

    我认为您遇到了在没有用户交互的情况下播放音频的问题。此线程中的更多信息。

    Is it possible to play audio without the user interact with the web before? how would I do that?

    简短的回答是你现在不能

    长答案是你可以通过一些技巧来做到这一点。

    【讨论】:

      猜你喜欢
      • 2012-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多