Reputation: 945
I'm trying to read in a wav file to run an fft on it but I keep running into an error with scipy.
import matplotlib.pyplot as plt
from scipy.io import wavfile as wav
import scipy
from scipy.fftpack import fft
import numpy as np
rate, data = scipy.io.wavfile.read('a1.wav')
fft_out = fft(data)
#matplotlib inline
plt.plot(data, np.abs(fft_out))
plt.show()
print 'exit'
The error I'm running into is:
Traceback (most recent call last):
File "test.py", line 9, in <module>
rate, data = scipy.io.wavfile.read('a1.wav')
File "/usr/local/lib/python2.7/site-packages/scipy/io/wavfile.py", line 275, in read
return fs, data
UnboundLocalError: local variable 'data' referenced before assignment
I thought it might have been an anaconda error so I removed anaconda but I'm still running into this issue.
If there is a better way to read wav files so that I can run ffts on them, let me know! Thanks!
Upvotes: 2
Views: 3256
Reputation: 913
Could it be becuse you need sox package.
if so, try installing sox. apt install sox
Also, check the header of the audio files,
soxi file_1.wav
and
apt install libav-tools
apt install ffmpeg
Upvotes: 0
Reputation: 5031
If you look at the code of the particular wavefile.read()
here on Github, you'll see that data
is only set in one place in the function:
elif chunk_id == b'data':
if not fmt_chunk_received:
raise ValueError("No fmt chunk before data")
data = _read_data_chunk(fid, format_tag, channels, bit_depth,
is_big_endian, mmap)
So this condition is never met when the Python interpreter runs the code, and we get the referenced before assignment exception.
A wav file consist of a header followed by a sequence of chunks. There are different types of chuncks. For example one can carry information about the data format, another the sampling rate, and then there is the one that contains the data. It seems in this case that Scipy's read
newer encounters this data
chunck, so it is very likely that there is something wrong with the wav file, or it might be of some newer format, which Scipy's implementation does not yet support.
Upvotes: 2