使用JavaScript播放通知声音

时间:2017-02-25 13:31:05

标签: javascript jquery html audio

我有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 1}}(我认为这是因为它在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);

this.$container.find('[data-uk-sortable]').on('stop.uk.sortable', function(e, el, type){
    //type is null here
}

this.$container.on('stop.uk.sortable', '[data-uk-sortable]', function(e, el, type){
    //type is null here
}

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

2 个答案:

答案 0 :(得分:2)

缓存上一个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 &&

答案 1 :(得分:0)

首先,由于setInterval()

,确保每2秒播放一次

您需要在响应之前和之后比较数据库中的消息行数...对我来说,简单的事情是将其传递到上一条消息中的隐藏<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);
相关问题