使用JavaScript播放通知声音



我有此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,并将其与新版本进行比较以确定是否播放音频文件。

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 &&

首先,由于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);

最新更新