简体   繁体   中英

How to play audio/sound in firebase-messaging-sw.js

I'm having an issue on how to play notification sound/audio file in firebase-messaging-sw.js . However the message was sent successfully. Here's what I've implemented so far

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);
});

From what i've read from multiple source, firebase cloud messaging is only providing sound notification in mobile devices.

However i want to play audio/sound when the notification is showing up in my desktop/browser. is there a way to play the audio in the browser?

i've also tried to play audio like this

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);
});

but still the audio notification still won't play.

and here's is request POST to FCM https://fcm.googleapis.com/fcm/send , with body params

{
  "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"
}

The notification is working with no problem, but there are no audio feedback when the notification shows.

I think you are encountering the problem of playing audio without user interaction. More info in this thread.

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

The short answer is you can't right now

The long answer is you could do that by doing some tricks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM