Emit a beeping sound with JavaScript

When you go to your favorite grocery store and the cashier processes your products, he or she will most likely scan them through a barcode scanner which will emit a sound — a sound that’s only there to signal that the scan was successful, and he or she can move onto the next product.

When you develop user interfaces for repetitive tasks, and especially when some sort of scanning is required, it might make a lot of sense to think of giving your users additional feedback so that they don’t have to go back and look at the screen every time they process an action — they can probably simply hear a confirmation sound, or feel an alarming buzz.

Let’s dig a bit deeper.

Bzzzzzz

If you’re giving your users a mobile device, the vibration API is a low-hanging fruit: by just navigator.vibrate(1000) you’ll have a device that buzzes for a second. Want to create interesting patterns? Then do something such as:

…and so on and so forth: the vibration API is absurdly easy, so I’m simply leaving it for you to experiment with it.

BEEP! BEEP! BEEP! BOOP!

Something a tad better is a snippet I found today, which simplifies audio feedback quite significantly:

1
2
3
4
5
6
7
8
9
10
11
12
13
a=new AudioContext() // browsers limit the number of concurrent audio contexts, so you better re-use'em

function beep(vol, freq, duration){
  v=a.createOscillator()
  u=a.createGain()
  v.connect(u)
  v.frequency.value=freq
  v.type="square"
  u.connect(a.destination)
  u.gain.value=vol*0.01
  v.start(a.currentTime)
  v.stop(a.currentTime+duration*0.001)
}

This snippet can be used to generate interesting sounds such as:

You can actually create songs with this kind of stuff (proof).

The WebAudio API is widely supported, so you shouldn’t have too many problems rolling it out across platforms:

At Namshi, we have provided our warehouse agents with devices to store, locate and move inventory — needless to say, combining these 2 APIs (vibration + sound) allows our efficiency to increase while working on more repetitive tasks.


Hi there! I recently wrote an ebook on web application security, currently sold on leanpub, the Amazon Kindle store and gumroad.

It contains 160+ pages of content dedicated to securing web applications and improving your security awareness when building web apps, with chapters ranging from explaining how to secure HTTP cookies with the right flags to understanding why it is important to consider joining a bug bounty program.

Feel free to skim through some of the free chapters published on this blog and, if the content seems interesting enough to you, grab a copy on leanpub, the Amazon Kindle store, gumroad or simply checkout right down below!

Buy the Web Application Security ebook for $6.99

In the mood for some more reading?

...or check the archives.