[英]Playing Notification Sound with JavaScript
我有这个script
可以从database
获取新消息
setInterval(function () {
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function (response) {
$(".msg_area").html(response);
}
});
}, 2000);
我试图在将新数据添加到database
立即向其添加声音,但是当我将其添加到上述script
,它每2 seconds
audio
一次audio
(我认为这是因为setInterval
中的audio
)
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 &&
从上面的代码中删除lastResponse &&
。
首先,由于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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.