Let's talk about some signal processing first. Since the maximum frequency of interest is 20KHz it becomes the Nyquist Frequency. The data thus needs to be generated at least at twice the Nyquist Rate which is 2*20KHz = 40KHz. Assuming this to be our sampling rate denoted by Fs, the duration between each sample of data is 1/Fs seconds. If we want the duration of generated frequency to be 2 seconds, we need 2/(1/Fs) = 2Fs number of data samples. If the desired frequency to be generated is f, then the nth sample value is found using the equation:
Web Audio API
AudioContext has a read-only attribute of sampling rate which is based on the device. Generally, this value is 44.1KHz. We will use this as sampling rate for generation of our signal. AudioContext also provides a read only destination attribute that represents the actual audio hardware. To play the audio via this destination, a source node needs to be connected to it. The source node should contain the buffer with the desired data. The following function achieves these.
In order, to test it we can quickly create a simple html page with a text box to read the desired frequency and a “Play” button to play the tone.
We can have the following code to call our “playFrequency” function when the “Play” button is clicked.
There is a lot more that one can do with Web Audio API. There are built-in oscillators that can be used to generate signals. The signal can be ramped up or down in a smoother fashion. In this blog I have just shown a vary simple of generating a tone. Enjoy playing around with it.