Sunday, September 4, 2011

Interesting Talk: "Effective Sketches"

I found this talk very interesting:
Effective sketches by Simon Brown

Play and stop an alarm sound using HTML5 audio in a Backbone view

I'm using Backbone.js in my toy project.
I had to adapt the example in my previous post so it could be used in a backbone view.
This is how I did it:
AlarmView = Backbone.View.extend({    
    events: {
        'click #alarmButton': 'alarmButtonPressed',

    initialize: function(){
        _.bindAll(this, 'render', 'alarmButtonPressed', 
                  'preSelectElements', 'playAlarm', 

    preSelectElements : function () {
        this.alarmText = this.$('#alarmTime');
        this.alarmButton = this.$('#alarmButton');

    render: function(){
        return this;

    alarmButtonPressed : function() {
    playAlarm : function () {    
        this.alarmSound = new Audio("alarm.wav");
        setTimeout(this.stopAlarm, this.alarmText.val() * 1000);;
    stopAlarm : function () {   
        this.alarmSound.startTime = 0;

    var alarmView = new AlarmView({el: $(document)});

And this is the HTML:
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <script src="libs/jquery-1.6.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="libs/underscore.js" type="text/javascript" charset="utf-8"></script>
        <script src="libs/backbone.js" type="text/javascript" charset="utf-8"></script>
        <script src="alarm.js" type="text/javascript" charset="utf-8"> </script>

        <input type="text" id="alarmTime" value="1"/>
        <button type="button" id="alarmButton">Start alarm</button>

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");

    function() {
        alarmSound = new Audio("alarm.wav");
            document.getElementById("alarmTime").value * 1000);;

function stopAlarm () {    
    alarmSound.startTime = 0;

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