新消息到达时播放声音

时间:2017-12-30 17:20:45

标签: javascript php jquery mysql xmlhttprequest

每次有人收到新消息时,我都会尝试播放声音。现在我正在制作一个聊天室,我希望每次新消息到达时(每当有人插入数据库中的聊天室表格时,正在观看聊天箱的人)播放声音。

<script type="text/javascript">
    function ajax(){
        var req = new XMLHttpRequest();
        req.onreadystatechange = function(){
            if (req.readyState == 4 && req.status == 200) {
                document.getElementById('chat').innerHTML = req.responseText;   
            }
        }
        req.open('GET', 'divisiones/chat.php', true);
        req.send();
    }
    //linea que hace que se refreseque la pagina cada segundo
    setInterval(function(){ajax();}, 1000);
</script>
 <div class="content-wrapper" onload="ajax();">
    <section class="content">
      <div class="row">
          <div class="col-md-12">
                <div class="box box-primary" style="background-color: #fffbf8;">
                    <div style="background: repeating-linear-gradient(-45deg, white, white 1px, #fffbf8 1px, #fffbf8 8px);">
                        <div class="wrap">
                            <div class="row">
                                <div id="caja-chat">
                                    <div id="chat"></div>
                                </div>

                                <form method="POST" action="division_chat.php?auth=<?php echo $salt_key_check; ?>">
                                    <input type="text" name="nombre" placeholder="Ingresa tu nombre">
                                    <textarea name="mensaje" placeholder="Ingresa tu mensaje"></textarea>
                                    <input type="submit" name="enviar" value="Enviar">
                                </form>

                                <?php
                                    if (isset($_POST['enviar'])) {

                                        $nombre = $_POST['nombre'];
                                        $mensaje = $_POST['mensaje'];


                                        $consulta = "INSERT INTO division_chat VALUES (NULL,'$session_login_usr', '$mensaje', '$fptime', '$log_ip', '$divisionpd')";

                                        $ejecutar = $con_db->query($consulta);

                                        if ($ejecutar) {
                                            echo "<embed loop='false' src='beep.mp3' hidden='true' autoplay='true'>";
                                        }
                                    }

                                ?>
                            </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
</div>

1 个答案:

答案 0 :(得分:0)

您需要在某处存储最后req.responseText值,以便检查新消息是否等于该值。

要存储req.responseText值,我将使用HTML5 localStorage

然后你可以这样做:

var LastMessage = localstorage.getItem('last_message');

if(req.responseText != LastMessage){

/////Play your sound here/////
$('#audio').play();

}

确保您的页面中有这个位置:

<audio id="audio" src="audio.mp3"></audio>