« Doing it My Way
Plex Alert »

Alarming Sounds

I am building a small web app and wanted to include some alarms. I spent too long looking online for examples, yet couldn't find any that I liked.

I really wanted to use vanilla JavaScript AudioContex without any library. I also wanted to generate the audio alerts without an external file. I found a few examples of things built with an oscillator, but they were all very complex and still didn't produce an alarm or siren like I wanted.

Most examples only had short buzz or beep, but I needed something that would repeat regularly.

I eventually built some sounds myself. Have a play, but be warned, they are loud and annoying. Please use them responsibly.

Note that these will not work with internet explorer. Use another browser.


The code is below:

<button onclick="alarm(1)">Beeping Alarm</button>
<button onclick="alarm(2)">Two Tone Warble Alarm</button>
<button onclick="alarm(3)">Siren Alarm</button>
<br/>
<button onclick="alarm(-1)">Stop Alarms</button>

<script>
var alarm_status = -1
var nextT = 0
var a=new AudioContext() 
var v // Placeholder for Oscillator
var u // Placeholder for Gain

function alarm(new_level){
    if (new_level == -1){
        nextT=0
        alarm_status = new_level
        v.stop()
        return
    }
    else if (new_level>0){
        try{
            // Try and stop the sound if it is already playing
            v.stop()
        }
        catch(e){
            //no problem if it wasn't already playing
        }
        alarm_status = new_level
        v =a.createOscillator()
        u=a.createGain()
        u.gain.value=0.01*100
        v.connect(u)
        u.connect(a.destination)
        T = a.currentTime
    }
    else{
        T = nextT
    }
    if (alarm_status >= 3){
        v.type = "square";
        u.gain.value=1
        v.frequency.exponentialRampToValueAtTime(440, T);
        v.frequency.exponentialRampToValueAtTime(880, T + 1);
        nextT = T+1
        timerID = window.setTimeout(alarm, 1000);
    }
    else if (alarm_status >= 2){
        v.type = "sine";
        u.gain.value=1
        v.frequency.setValueAtTime(880,T)
        v.frequency.setValueAtTime(440,T+0.5)
        nextT = T+1
        timerID = window.setTimeout(alarm, 1000);
    }
    else if (alarm_status >= 1){
        v.type = "sine";
        v.frequency.value=440
        u.gain.setValueAtTime(1,T)
        u.gain.setValueAtTime(0,T+0.5)
        nextT = T+1
        timerID = window.setTimeout(alarm, 1000);
    }
    try{
        v.start(T)
    }
    catch(e){
        return
    }
}
</script>
Go Top
Previous:
« Doing it My Way
Next:
Plex Alert »

Comments

I would love to know what you think. To comment on this article, send me an email

No comments yet.