How to plot a waveform from wav file in python?

6.7k Views Asked by At
import os
import scipy.io
import scipy.io.wavfile
import numpy as np
import matplotlib.pyplot as plt
dataset_path = os.path.join(os.environ['HOME'], 'shared', 'data', 'assignment_1')
wavedata = os.path.join(dataset_path, 'example.wav')
   
fs, audio_buffer = scipy.io.wavfile.read(wavedata)

And I kinda cannot understand how to further use matplotlib.pyplot Would be grateful for any advice or right documentation!

1

There are 1 best solutions below

0
On

this will plot the wav audio file in its native time domain as a time series

import os
import scipy.io
import scipy.io.wavfile
import numpy as np
import matplotlib.pyplot as plt

myAudioFilename = 'aaa.wav'  #  plot this wav file     ~/audio/aaa.wav

dataset_path = os.path.join(os.environ['HOME'], 'audio') # homedir -> audiodir -> my wav files
wavedata = os.path.join(dataset_path, myAudioFilename)
   
sampleRate, audioBuffer = scipy.io.wavfile.read(wavedata)

duration = len(audioBuffer)/sampleRate

time = np.arange(0,duration,1/sampleRate) #time vector

plt.plot(time,audioBuffer)
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.title(myAudioFilename)
plt.show()

Notice the plot accurately renders time which is derived from the WAV file headers which defines the sample rate ... along with bit depth and channel count ... those attributes give the code ability to parse the binary WAV file byte by byte which get rendered as a series of points on the displayed curve ( each point is an audio sample for given channel )