How do I play a sound when an element changes, lik

2019-03-25 12:48发布

I want a sound to play when an element changes on a page. I know how to do this, but I can't get it to play only on the first change, and don't do it later, until the user focuses the window (tab) and blurs it again.

My current code:

var notif = new Audio('http://cycle1500.com/sounds/infbego.wav');
if (window.innerHeight === window.outerHeight) {
  $(window).bind('DOMNodeInserted', function() {
      notif.play();
  });
}

2条回答
对你真心纯属浪费
2楼-- · 2019-03-25 13:21

Use a variable to represent whether the sound should be played or not.

var shouldPlayAlertSound = true,
    notif = new Audio('http://cycle1500.com/sounds/infbego.wav');
if (window.innerHeight === window.outerHeight) {
  $(window).bind({
    'DOMNodeInserted': function() {
      if (shouldPlayAlertSound) {
        notif.play();
      }
      shouldPlayAlertSound = false;
    }, blur: function() {
      shouldPlayAlertSound = true;
    } 
  });
}

Edit: I've tested this working on Firefox, Safari, and Opera (except for the innerHeight check). (Chrome doesn't support playing WAV audio files, only the MP3, AAC, or Ogg Vorbis formats.)

查看更多
孤傲高冷的网名
3楼-- · 2019-03-25 13:28

If this is your only DOMNodeInserted handler, I'd just remove it when the work is done (making all future insertions cheaper), like this:

notif = new Audio('http://cycle1500.com/sounds/infbego.wav');
if (window.innerHeight === window.outerHeight) {
  $(window).bind({
    'DOMNodeInserted': function() { 
      notif.play(); 
      $(window).unbind('DOMNodeInserted'); 
    }
  });
}

If it's not the only handler that's workable too, just make it a named function:

notif = new Audio('http://cycle1500.com/sounds/infbego.wav');
if (window.innerHeight === window.outerHeight) {
  function play() { notif.play(); $(window).unbind('DOMNodeInserted', play); }
  $(window).bind({
    'DOMNodeInserted': play
  });
}
查看更多
登录 后发表回答