How to plot a wav file How to plot a wav file python python

How to plot a wav file


You can call wave lib to read an audio file.

To plot the waveform, use the "plot" function from matplotlib

import matplotlib.pyplot as pltimport numpy as npimport waveimport sysspf = wave.open("wavfile.wav", "r")# Extract Raw Audio from Wav Filesignal = spf.readframes(-1)signal = np.fromstring(signal, "Int16")# If Stereoif spf.getnchannels() == 2:    print("Just mono files")    sys.exit(0)plt.figure(1)plt.title("Signal Wave...")plt.plot(signal)plt.show()

you will have something like:enter image description here

To Plot the x-axis in seconds you need get the frame rate and divide by size of your signal, you can use linspace function from numpy to create a Time Vector spaced linearly with the size of the audio file and finally you can use plot again like plt.plot(Time,signal)

import matplotlib.pyplot as pltimport numpy as npimport waveimport sysspf = wave.open("Animal_cut.wav", "r")# Extract Raw Audio from Wav Filesignal = spf.readframes(-1)signal = np.fromstring(signal, "Int16")fs = spf.getframerate()# If Stereoif spf.getnchannels() == 2:    print("Just mono files")    sys.exit(0)Time = np.linspace(0, len(signal) / fs, num=len(signal))plt.figure(1)plt.title("Signal Wave...")plt.plot(Time, signal)plt.show()

New plot x-axis in seconds:

enter image description here


Alternatively, if you want to use SciPy, you may also do the following:

from scipy.io.wavfile import readimport matplotlib.pyplot as plt# read audio samplesinput_data = read("Sample.wav")audio = input_data[1]# plot the first 1024 samplesplt.plot(audio[0:1024])# label the axesplt.ylabel("Amplitude")plt.xlabel("Time")# set the title  plt.title("Sample Wav")# display the plotplt.show()


Here's a version that will also handle stereo inputs, based on the answer by @ederwander

import matplotlib.pyplot as pltimport numpy as npimport wavefile = 'test.wav'with wave.open(file,'r') as wav_file:    #Extract Raw Audio from Wav File    signal = wav_file.readframes(-1)    signal = np.fromstring(signal, 'Int16')    #Split the data into channels     channels = [[] for channel in range(wav_file.getnchannels())]    for index, datum in enumerate(signal):        channels[index%len(channels)].append(datum)    #Get time from indices    fs = wav_file.getframerate()    Time=np.linspace(0, len(signal)/len(channels)/fs, num=len(signal)/len(channels))    #Plot    plt.figure(1)    plt.title('Signal Wave...')    for channel in channels:        plt.plot(Time,channel)    plt.show()

enter image description here