Saturday, September 3, 2011

Play and stop an alarm sound using HTML5 audio tag

In my current toy project, I wanted to reproduce an alarm sound every time some event happened.
The alarm sound I found was a bit long, so I wanted to stop it after a given time stored in the application settings.

It seems that HTML5 audio doesn't have a stop method. It has only a pause method. So following the advises in here and here, I managed to write the following code to check how it worked before adding it to my toy project:

var alarmButton = document.getElementById("alarmButton");

alarmButton.addEventListener(
    "click", 
    function() {
        alarmSound = new Audio("alarm.wav");
        window.setTimeout(stopAlarm, 
            document.getElementById("alarmTime").value * 1000);
        alarmSound.play();
    }, 
    true
);

function stopAlarm () {    
    alarmSound.pause();
    alarmSound.startTime = 0;
} 

This is the HTML file:
<!DOCTYPE HTML>
<html>    
    <body>
        <input type="text" id="alarmTime" value="1"/>
        <button type="button" id="alarmButton">Start alarm</button>
    </body>
    
    <script src="alarm.js" type="text/javascript" charset="utf-8">
    </script>    
</html>

No comments:

Post a Comment