我有一个使用通知的网站(gitter.im),我希望在推送通知时运行声音。如何将此代码添加到通知中?
(function() {
var a = document.createElement('audio')
a.setAttribute('autoplay', true)
a.setAttribute('src', 'http://www.soundjay.com/button/beep-03.mp3')
})();

答案 0 :(得分:2)
您可以使用HTML5音频API,但它在服务工作者中无效。
当浏览器收到通知时发出声音的唯一方法是通过postMessage(),您可以通知您的网页发出声音,但只有在浏览器中打开主网站页面时它才会起作用。
(Chrome ServiceWorker postMessage)
var track = new Audio("http://oringz.com/oringz-uploads/sounds-874-gets-in-the-way.mp3");
track.play();

更多信息: http://www.html5rocks.com/en/tutorials/webaudio/intro/
答案 1 :(得分:0)
这似乎有效:
(function(Notif) {
function play() {
var a = document.createElement('audio')
a.setAttribute('autoplay', true)
a.setAttribute('src', 'http://www.soundjay.com/button/beep-03.mp3');
}
window.Notification = function(title, option) {
var notif = new Notif(title, option);
play();
return notif;
};
for (var key in Notif) {
if (Notif.hasOwnProperty(key)) {
window.Notification[key] = Notif[key];
}
}
})(Notification);