简体   繁体   English

如何在元素更改时播放声音,例如SO Chat吗?

[英]How do I play a sound when an element changes, like SO Chat does?

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

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). 编辑:我已经在Firefox,Safari和Opera上测试了这个 (除了innerHeight检查)。 (Chrome doesn't support playing WAV audio files, only the MP3, AAC, or Ogg Vorbis formats.) (Chrome不支持播放WAV音频文件,仅支持MP3,AAC或Ogg Vorbis格式。)

If this is your only DOMNodeInserted handler, I'd just remove it when the work is done (making all future insertions cheaper), like this: 如果这是你唯一的DOMNodeInserted处理程序,我只需在工作完成后删除它(使所有未来的插入更便宜),如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM