How to generate a simple continuous tone in the browser using JavaScript?

How to generate a simple continuous tone in the browser using JavaScript?
0.0 0

#1

Goal: In the browser. User presses mouse button -> A continuous tone plays -> User releases mouse button -> The tone stops.

I can handle the mouse press event, it’s the audio part I’m having a difficult time with.

I have looked at the Web Audio API and I can’t make heads or tails of it. I can’t seem to find a simple user friendly library, piece of code or guide to achieve my goal. There’s gotta be some way to do this that doesn’t involve me first getting a sound engineering degree. Ideally I’m looking for a library that has code like this:

function playTone(frequencyHz) {
  let myGDamnTone = sound engineering mumbo jumbo * frequencyHz;
  ...
  return myGDamnTone;
}

Where I can then simply go:

playTone(441);

If there isn’t any such solution out there, I’d like the next best thing. I’m looking for the simplest solution to achieve this goal and by simplest I mean the one that will require as few parameter inputs and lines of code from me as possible.


#2

The OscillatorNode should work:
https://developer.mozilla.org/nl/docs/Web/API/OscillatorNode


#3

It is actually quite fun to play with: http://codepen.io/benjaminvanzwienen/pen/ggpWza?editors=1010