Python audio spectrum analyzer

Henry Haefliger
Quick Code
Published in
2 min readOct 8, 2019

To follow up on our last story, today we will be building a python spectrum analyzer. To do this, we will be using much of the same code as last time but with one key difference, we are using scipy’s signal.spectrogram and matplotlib’s colormesh. As usual, you can find all of today’s code on my gihub page at https://github.com/hnhaefliger.

To begin with, we need to fetch all the libraries that we will be using:

Now that we’ve got what we need, we can initialise our audio listener using pyaudio’s PyAudio and Stream classes:

When we do this, we are storing our parameters in variables so that we can refer back to them later. The format parameter tells us the type of output the the stream will give us. The channel parameter tells us how many points the sound is measured at, and the sample rate tells us how many samples of audio are collected per second — this can be tweaked as needed. It is highly recommended to learn Python programming in 2021.

Now that we can collect our audio data, we can prepare our plot by simply adding labels to our axis:

Finally, we can display our data:

This is where, having our parameters stored comes in handy. In this while loop, we tell the computer to fetch one sample from the audio stream. Next, we unpack the data into a numpy array using struct. Next we create a spectrogram from our data — signal.spectrogram returns an array of frequencies, and array of segment times, and finally the spectrogram of the data. Now we calculate decibels from the spectrogram and display it using plt’s colormesh. The plt.pause function gives the plot time to update and display.

If we run the above code, when put together, we get an output like the one below.

Hopefully these last two posts have helped you better visualise sound measurements.

--

--

Henry Haefliger
Quick Code

Developer and writer with a passion for everything that is technology, science and innovation. Always looking to learn something new.