如何在javascript中播放音乐

时间:2018-05-17 21:24:41

标签: javascript html notifications

你好,我有一个用javascript编写的html5桌面推送通知,当该通知出现时,我想播放声音影响,以便用户知道有通知让他们看看

继承我的代码

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

和heres我的mp3文件

alarm.mp3

2 个答案:

答案 0 :(得分:1)

你可以演这样的歌:

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

选中此related topic

答案 1 :(得分:0)

使用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 () {
      var audio = new Audio('/pathTo/alarm.mp3');
      audio.play();
      window.open("http://carnes.cc");      
    };
    setTimeout(notification.close.bind(notification), 7000); 
}