用 JavaScript 播放通知声音

Oke*_*ega 0 html javascript audio jquery

我有这个script来从我的database

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

我尝试在向其中添加新数据后立即为其添加声音,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);
Run Code Online (Sandbox Code Playgroud)

所以请我问。如何仅在新数据添加到数据库时播放声音?

gyr*_*yre 5

缓存最后一个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);
Run Code Online (Sandbox Code Playgroud)

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