JavaScript - How can I get the frequency of a sound in real time?

4

Could someone give me a clue how to get the frequency of a sound in real time with javascript? Thanks.

    
asked by Joseph Alberto Morthimer Leon 01.11.2016 в 19:21
source

1 answer

1

The API available to do this is AudioContext , you need to do 4 things:

  • Create an analyzer node, which allows you to sample the audio piece by piece and know, for example, the signal strength at each point.
  • Create a processor node, which allows you to process the audio as it plays.
  • In the processor, and using the analyzer, you take the frequency samples.
  • Connect everything together to: Display the current intensity of the audio and send it also to the speaker or output.
  • With the frequency samples (obtained with fast Fourier transform or FFT) you can search the frequencies with greater intensity and determine the dominant frequency. There are many methods to calculate the pitch, here I used a very simple and not very precise one that is based on the signal with more energy, but the human ear does not work in this way, so it may take some work to adapt the calculation of the "audible" frequency ..

    The example is in this JSFIDDLE , because the StackSnippets do not allow capturing the microphone. Notice that the green line is the frequency shown above. It works pretty well with a tone generator like this .

    Keep in mind that these are quite new APIs and although there is good support it is an option that you should use as Progressive Enhancement, so you should only include it in browsers that support it. It is also very useful in applications made with Electron or Apache Cordoba since they are based on Chromium and it supports these APIs very well.

        
    answered by 01.11.2016 / 19:49
    source