Convert audio files to graph visualisation

In this article we shall how we can convert an audio file to its graph visualisation. The graph is plotted by taking the frequencies of the audio file as a numpy array. Let us get started.

Libraries needed

We will need the following two libraries for this task.

  1. soundfile
  2. matplotlib

both can be installed via pip as

pip install soundFile

and

pip install matplotlib

Soundfile

Soundfile is a python library that can be used to read and write audio files. We will use this library to convert our audio to a numpy array. The numpy array will have frequencies of our audio file. Simple usage of this library is,

read audio file

The read function from the soundfile library return a tuple. The first value is the data which is our numpy array and the next one is the samplerate.

The sounfile also provides a write() function which can be used to convert the numpy array back to audio file.

Matplotlib

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. We will create our graph using this library. The basic usage is,

plot graph using numpy array

The plot function from pyplot plots the graphs for us. The data is the numpy array that we have generated using the above soundfile library. The show() funciton shows us the graph like a pop up. we can also the save the figure instead of displaying it.

Putting it all together the code looks like this.

plot graph using audio

This will generate a graph like this.

Graph generated using pyplot for the audio file

We can save the image manually using the save icon from the popup or we can use the savefig() method from the pyplot module like pyplot.savefig(“filename”) instead of pyplot.show()

Leave a Reply

Your email address will not be published. Required fields are marked *