Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

play sound clip when php/mysql if statement is true?

Tags:

php

mysql

hi i have a message alert box that appears when a user gets a new message, what i want to do is add sound to this box when it pops up, i am using a php if statement to check when a user gets a new message and i have tried adding sound by doing the following but its not working please can someone show me how to do this. thanks.

<?php
$check_new_chats = check_new_chats();
while ($chat = mysql_fetch_array($check_new_chats)) 
if (isset($_SESSION['user_id'])) { 
        if ($chat['to_user_id'] == $_SESSION['user_id']){ 
        echo( "<embed name='sound_file' src='/assets/music/sound_file.mp3' loop='true' hidden='true' autostart='true'/>"); ?>
like image 231
James Pale Avatar asked Oct 04 '22 14:10

James Pale


2 Answers

<?php
$check_new_chats = check_new_chats();
while ($chat = mysql_fetch_array($check_new_chats)) 
if (isset($_SESSION['user_id'])) { 
    if($chat['to_user_id'] == $_SESSION['user_id']){ 
        echo '<script type="text/javascript">play_sound();</script>';
    }
}
?>

Here's the Javascript function:

<script type="text/javascript">
    function play_sound() {
        var audioElement = document.createElement('audio');
        audioElement.setAttribute('src', '/assets/music/sound_file.mp3');
        audioElement.setAttribute('autoplay', 'autoplay');
        audioElement.load();
        audioElement.play();
    }
</script>
like image 58
Raphael Caixeta Avatar answered Oct 10 '22 04:10

Raphael Caixeta


According to the question:

hi i have a message alert box that appears when a user gets a new message, what i want to do is add sound to this box when it pops up

You already have some sort of javascript function that displays an alert box when needed. Use the info from this answer to play a sound with it.

<audio id="soundHandle" style="display: none;"></audio>
<script>
  soundHandle = document.getElementById('soundHandle');
  soundHandle.src = '/assets/music/sound_file.mp3';
</script>



//With your message alert function....
alert("Message box");
soundHandle.play();
like image 30
kmoney12 Avatar answered Oct 10 '22 03:10

kmoney12