0

Hello there I have a html5 desktop push notification written in javascript and when that notification comes up I want to play a sound affect so that the user knows there is a notification for them to look at

heres my code

function notifyMe() {
  if (!("Notification" in window)) {
    alert("This browser does not support system notifications");
  }
  else if (Notification.permission === "granted") {
    notify();
  }
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {
      if (permission === "granted") {
        notify();
      }
    });
  }

  function notify() {
    var notification = new Notification('TITLE OF NOTIFICATION', {
      icon: 'http://carnes.cc/jsnuggets_avatar.jpg',
      body: "Hey! You are on notice!",
    });

    notification.onclick = function () {
      window.open("http://carnes.cc");      
    };
    setTimeout(notification.close.bind(notification), 7000); 
  }

}
notifyMe();

and heres my mp3 file

alarm.mp3

Arnav Nath
  • 71
  • 2
  • 3
  • 12
  • Ideally, you leave the notification and its sounds up to the system. Everyone has their own notification preferences. Plus, you can't always guarantee the exact timing of your notification. The user might not be present... the notification might be saved for when they return. – Brad May 17 '18 at 21:33
  • Possible duplicate of [Playing audio with Javascript?](https://stackoverflow.com/questions/9419263/playing-audio-with-javascript) – Kevin Raoofi May 17 '18 at 21:41

2 Answers2

1

You can play a song like that :

var audio = new Audio('alarm.mp3');
audio.play();

Check this related topic

Philippe
  • 960
  • 2
  • 12
  • 29
0

Call the play from the notify() method:

function notify() {
    var notification = new Notification('TITLE OF NOTIFICATION', {
      icon: 'http://carnes.cc/jsnuggets_avatar.jpg',
      body: "Hey! You are on notice!",
    });

    notification.onclick = function () {
      var audio = new Audio('/pathTo/alarm.mp3');
      audio.play();
      window.open("http://carnes.cc");      
    };
    setTimeout(notification.close.bind(notification), 7000); 
}
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108