top of page

JavaScript Sound Visualizer


I woke up Saturday and was thinking about Discrete Fourier Transforms (you know normal things) and wondered how hard it would be to implement a simple guitar tuner in Javascript.


I started off my journey by looking up how one would get microphone input on a webpage.


Which, due to modern web standards, is actually pretty easy. Check out this Mozilla page on the Web Audio API

The parameters to createBuffer(1,5000,10000) are (channel count, samples, sample rate) so in this case I'm creating a buffer for a Mono channel and I'm only sampling at 10,000Hz for 5000 samples. I didn't really care about the entire human hearing range, I wanted to have enough samples to determine the base frequency of an instrument.

Interestingly, in my research for how to capture audio, I found out that the audio library has built in functions for doing Fourier Transforms.

Here is the whole javascript file required to create the waveform graph above!


requestAnimationFrame(update)

In the Update, the call to getFloatFrequencyData(dataBuff) is what does the FFT and gets the data bins.

In the Draw function it then just plots all of the bins to create that cool spectrum visualiztion.

Some things to note:

In the examples I was looking at (Check out this example that the Mozilla page references) they were using a older version of the getUserMedia. Apparently the new way to do this is the navigator.mediaDevices style.

In the getUserMedia, the {audio: true} just tells the browser that we only want access to the mic.

I was going to embedded this code in to my Wix hosted web page, so that you could see it working for real, And interestingly it works in all browsers (that I tested) except Chrome. The reason for this is the way that Wix embeds code into the page. It uses an IFrame. I was reading the justification for why chrome blocks it and it comes down to security. See the way a page currently works, if you allow a page access to your microphone, it is implied that your whole page gets access. Things inside of an IFrame can be pieces of javascript or ads or things hosted on external sites. This is potentially a security issue if you allowed a page access to your mic a rouge piece of code in an iframe could forward it off.

Chrome therefore disables permissions to iframes by default, and allows a coder to give it explicit permission using a tag.

Unfortunately Wix doesn't allow me to mess with the iframe tags.

But it was an interesting look in to the very complicated world of web security!

Comments


bottom of page