Skip to content

Instantly share code, notes, and snippets.

@groakat
Created July 21, 2015 11:43
Show Gist options
  • Save groakat/b9b385e7a81fefd66ca9 to your computer and use it in GitHub Desktop.
Save groakat/b9b385e7a81fefd66ca9 to your computer and use it in GitHub Desktop.
def SpecGen(self, filepath):
"""
Code to generate spectrogram adapted from code posted on https://mail.python.org/pipermail/chicago/2010-December/007314.html by Ken Schutte (kenshutte@gmail.com)
"""
sr, x = scipy.io.wavfile.read(filepath)
## Parameters
nstep = int(sr * self.specNStepMod)
nwin = int(sr * self.specNWinMod)
nfft = nwin
# Get all windows of x with length n as a single array, using strides to avoid data duplication
#shape = (nfft, len(range(nfft, len(x), nstep)))
shape = (nfft, ((x.shape[0] - nfft - 1)/nstep)+1)
strides = (x.itemsize, nstep*x.itemsize)
x_wins = np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
# Apply hamming window
x_wins_ham = np.hamming(x_wins.shape[0])[..., np.newaxis] * x_wins
# compute fft
fft_mat = np.fft.fft(x_wins_ham, n=nfft, axis=0)[:(nfft/2), :]
# log magnitude
fft_mat_lm = np.log(np.abs(fft_mat))
return fft_mat_lm.T
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment