DEV Community

Purity-Nyagweth
Purity-Nyagweth

Posted on

How to Plot an audio file using Matplotlib

Introduction

Plotting and visualizing an audio file is one of the most important processes in audio analysis. Audio analysis is the process of transforming, exploring, and interpreting audio signals recorded by digital devices so as to extract insights from the audio data.

In this article, we are going to plot a waveform of an audio file with matplotlib.

Prerequisites

  • Python installed
  • Numpy installed
  • Matplotlib installed
  • Background in data analysis

Importing module and libraries

As a first step, let's import the modules and libraries that we will need.



import wave
import matplotlib.pyplot as plt 
import numpy as np


Enter fullscreen mode Exit fullscreen mode

We will use wave module and numpy to preprocess the audio. We will use matplotlib for plotting the audio.

Loading the Audio file

The audio file that we will use is a wave file.
Let's load the wave file that we want to plot



obj = wave.open('audio_file.wav', 'rb')


Enter fullscreen mode Exit fullscreen mode

Getting Audio parameters

Let's print out the audio parameters such as number of channels, sample width, etc.
We will use .getparams() method of the wave module



print('Parameters:', obj.getparams())


Enter fullscreen mode Exit fullscreen mode

Output: Parameters: _wave_params(nchannels=1, sampwidth=2, framerate=22050, nframes=81585, comptype='NONE', compname='not compressed')

Now let's get the parameters that we will need for plotting the audio.

  • Sample frequency, this is the number of samples per second


sample_freq = obj.getframerate()


Enter fullscreen mode Exit fullscreen mode
  • Number of samples, this is the total number of samples or frames in the audio file


n_samples = obj.getnframes()


Enter fullscreen mode Exit fullscreen mode
  • Signal wave, this is the wave amplitude which is the sound intensity.


signal_wave = obj.readframes(-1)


Enter fullscreen mode Exit fullscreen mode
  • Audio length, this is the duration of the audio.


duration = n_samples/sample_freq


Enter fullscreen mode Exit fullscreen mode

Creating numpy objects

Let's create a numpy object from the signal_wave. This will be plotted on the y-axis.



signal_array = np.frombuffer(signal_wave, dtype=np.int16)


Enter fullscreen mode Exit fullscreen mode

Let's create a numpy object from duration. This will be plotted on the x-axis



time = np.linspace(0, duration, num=n_samples)


Enter fullscreen mode Exit fullscreen mode

Creating an audio plot



plt.figure(figsize=(15, 5))
plt.plot(time, signal_array)
plt.title('Audio Plot')
plt.ylabel(' signal wave')
plt.xlabel('time (s)')
plt.xlim(0, time) #limiting the x axis to the audio time
plt.show()


Enter fullscreen mode Exit fullscreen mode

Output:

Output of the plot

Conclusion

In this article, we've learnt how to plot a waveform of an audio file. Apart from plotting the waveform, another plot we can get from an audio file is frequency spectrum. For the frequency spectrum, we plot sample frequency against time. To learn how to plot a frequency spectrum, checkout this link.

Credits

Audio Processing Basics(Assembly AI)
Audio Analysis(altexsoft)

Top comments (3)

Collapse
 
chrisgreening profile image
Chris Greening

Really neat tutorial, thanks for posting! I love all the different things you can do with matplotlib, lots of fun projects to do with it

Collapse
 
dendihandian profile image
Dendi Handian

what kind of insight you usually get from audios?

Collapse
 
puritye profile image
Purity-Nyagweth

An example is sentimental and emotional insights