sarahholden
sarahholden

Reputation: 650

Create a countdown timer using javascript with alarm sound

I'm trying to create a simple countdown timer that will play an alarm sound at the end (this will be for a recipe site).I found a script for a simple countdown timer, but I am having trouble implementing an alarm sound at the end. I am attempting to use SoundManager2 for the alarm sound. I am new to programming so any tips would help!

Thank you!!

here is my countdown timer script:

function countdown( elementName, minutes, seconds )
{
    var element, endTime, hours, mins, msLeft, time;

    function twoDigits( n )
    {
        return (n <= 9 ? "0" + n : n);
    }

    function updateTimer()
    {
        msLeft = endTime - (+new Date);
        if ( msLeft < 1000 ) {
            mySound.play();

            //element.innerHTML = "countdown's over!";
        } else {
            time = new Date( msLeft );
            hours = time.getUTCHours();
            mins = time.getUTCMinutes();
            element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
            setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
        }
    }

    element = document.getElementById( elementName );
    endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
    updateTimer();
}

countdown( "countdown", 0, 15 );

Upvotes: 0

Views: 6103

Answers (1)

Didatus
Didatus

Reputation: 900

You are using mySound.play(), but i can't see any soundfile loading. With SoundManager you have to "create" a sound object first on which you can use the play method later. One simple example in the docu of sm2:

var mySoundObject = soundManager.createSound({
 id: 'mySound',
 url: '/audio/mysoundfile.mp3'
});
mySoundObject.play();

If you want the possibility off running this on an iPhone or iPad you should call mySoundObject.destruct() after play. Otherwise you will probably hear nothing after first play.

Upvotes: 1

Related Questions