Question

I'm trying to test a Python script that hopefully produces an audio spectrogram from a wav file. I assume I need to input a path to a wav, but I am getting an error: IndexError: list index out of range when I tried it by entering it here:

sr,x = scipy.io.wavfile.read('mySoundFile.wav')

I also tried the path as an argument in the command line, but I am not getting it right. Any help?

http://mail.python.org/pipermail/chicago/2010-December/007314.html

"""
Compute and display a spectrogram.
Give WAV file as input
"""
import matplotlib.pyplot as plt
import scipy.io.wavfile
import numpy as np
import sys

wavfile = sys.argv[1]

sr,x = scipy.io.wavfile.read('BeatBoy01.wav')

## Parameters: 10ms step, 30ms window
nstep = int(sr * 0.01)
nwin  = int(sr * 0.03)
nfft = nwin

window = np.hamming(nwin)

## will take windows x[n1:n2].  generate
## and loop over n2 such that all frames
## fit within the waveform
nn = range(nwin, len(x), nstep)

X = np.zeros( (len(nn), nfft/2) )

for i,n in enumerate(nn):
    xseg = x[n-nwin:n]
    z = np.fft.fft(window * xseg, nfft)
    X[i,:] = np.log(np.abs(z[:nfft/2]))

plt.imshow(X.T, interpolation='nearest',
    origin='lower',
    aspect='auto')

plt.show()
Was it helpful?

Solution

You can use this try/except to get around the IndexError:

try:
   wavefile = sys.argv[1]
except IndexError:
   wavfile = 'BeatBoy01.wav'

sr,x = scipy.io.wavfile.read(wavfile)

This effectively sets the default file to BeatBoy01.wav if no argument is passed to the script. Keep in mind that BeatBoy01.wav should be in the same directory from where the script is executed for this to work.

For easier argument parsing, have a look at the OptParse library.

OTHER TIPS

Dont use "wavfile" as a variable, it is the name of the library.

Try this:

inputFile = sys.argv[1]

sr,x = scipy.io.wavfile.read(inputFile)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top