5

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'/>"); ?>
James Pale
  • 193
  • 3
  • 6
  • 18

2 Answers2

3
<?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>
Raphael Caixeta
  • 7,808
  • 9
  • 51
  • 76
1

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();
Community
  • 1
  • 1
kmoney12
  • 4,413
  • 5
  • 37
  • 59