Arnav Nath
Arnav Nath

Reputation: 81

how to play music in javascript

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

Upvotes: 0

Views: 2956

Answers (2)

Philippe
Philippe

Reputation: 1030

You can play a song like that :

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

Check this related topic

Upvotes: 1

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

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

Upvotes: 0

Related Questions