'Using matplotlib to create a spectrogram of a wavfile

import scipy.io.wavfile as wav
import matplotlib.pyplot as plt
import scipy
sample_rate, X = wav.read("/Users/sinaastani/Downloads/partynextdoor.wav")
X = scipy.mean(X, axis=1)
plt.specgram(X, Fs=sample_rate, xextent=(0,30))

I get an error whenever I run the code above:

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/axes/_axes.py:7017: RuntimeWarning: divide by zero encountered in log10
  Z = 10. * np.log10(spec)

This occurs with several wav files that I have tried. I'm simply trying to replicate an example from "Building Machine Learning Systems with Python - Second Edition".

The wavfile.read function returns a numpy array. It looks like at the beginning and end of this array, there are a bunch of 0 values so when it tries to calculate log(0) it is undefined. What is the appropriate to deal with this? Should I simply get rid of 0 values from the array?



Solution 1:[1]

Use the parameter NFFT of plt.specgram(). Because this parameter defaults to 256, it causes the error. You can increase this number by multiplying it to 2 to the extent by which the error disappears. Try 512 - 1024 - 2048 , ... and the problem is solved!:)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mojtaba Abdi Kh.