【问题标题】:Playing Notification Sound with JavaScript使用 JavaScript 播放通知声音
【发布时间】:2017-02-25 13:31:04
【问题描述】:

我有这个script 来接收来自我的database 的新消息

setInterval(function () {
        $.ajax({
            type: "GET",
            url: "get_chat.php",
            dataType: "html",
            success: function (response) {
                $(".msg_area").html(response);
            }
        });
    }, 2000);

我会尝试在将新数据添加到database 后立即为其添加声音,但是当我添加到上面的script 时,它会播放audio 每个2 seconds(我认为这是因为它在setInterval)

setInterval(function () {
        $.ajax({
            type: "GET",
            url: "get_chat.php",
            dataType: "html",
            success: function (response) {
                $(".msg_area").html(response);
                var audio = new Audio('audio_file.mp3');
                audio.play();
            }
        });
    }, 2000);

所以请教一下。如何仅在将新数据添加到数据库时播放声音?

【问题讨论】:

  • 每次response来了吗?

标签: javascript jquery html audio


【解决方案1】:

缓存最后一个response,与新版本比较,判断是否播放音频文件。

var lastResponse = ''

setInterval(function() {
  $.ajax({
    type: "GET",
    url: "get_chat.php",
    dataType: "html",
    success: function(response) {
      $(".msg_area").html(response)
      if (lastResponse && response !== lastResponse) {
        var audio = new Audio('audio_file.mp3')
        audio.play()
      }
      lastResponse = response
    }
  });
}, 2000);

编辑:如果您希望在response 首次进入时播放音频,请从上面的代码中删除 lastResponse &&

【讨论】:

    【解决方案2】:

    首先,确保它每 2 秒播放一次,因为 setInterval()

    您需要在响应之前和之后比较数据库中的消息行数。对我来说,简单的事情是在最后一条消息中将其传递到隐藏的 <div>

    setInterval(function () {
            var message_num = // get the number from the last message
            $.ajax({
                type: "GET",
                url: "get_chat.php",
                dataType: "html",
                success: function (response) {
                    $(".msg_area").html(response);
                    var new_message_num = // get the number from the last message after response
                    if(new_message_num > message_num){
                      var audio = new Audio('audio_file.mp3');
                      audio.play();
                    }
                }
            });
        }, 2000);
    

    【讨论】:

    • 如何在firefox中使用它?它在不播放声音的情况下显示警告。 Autoplay is only allowed when approved by the user, the site is activated by the user, or media is muted.
    猜你喜欢
    • 2010-10-01
    • 2015-02-04
    • 1970-01-01
    • 2010-10-07
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    相关资源
    最近更新 更多