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.


In the mood for some more reading?

...or check the archives.