I'm messing around with reading in a sine wave and performing some calculations in Python. I wonder, though, if the data types established in numpy are causing any trouble. My main goal here is to read in a .wav file and find amplitudes for samples. I'd rather not use a command line tool like sax or ffmpeg:
f = wave.open('sine.wav','rb') #3 second long sine wav
nchannels, sampwidth, framerate, nframes, comptype, compname = f.getparams()[:6]
if sampwidth != 2:
raise ValueError("Only supports 16 bit audio formats")
if nchannels == 2:
nframes*=2 #this seems to give me all data when I read in a 2-channel wave
byteList = np.fromstring(f.readframes(nframes), dtype = np.int16)
f.close()
byteList.astype(float) #attempt to change type to perform the following operations
maximum = max(byteList)
minimum = min(byteList)
peak = (abs(maximum)+abs(minimum))/2) #find a good max amplitude. This fails
#RuntimeWarning: overflow encountered in short_scalars. I thought I changed type!
#I check to see the indices where the max amplitude occurs. I get no results.
for i in byteList[0:nframes]:
if peak <= (byteList[i]):
print('These are the indices where the maximum occurs: {}'.format(i))
#Find the rms value. This gets me .7344... Close, I guess.
total = 0
for i in byteList[0:nframes]:
total+=(((byteList[i])/peak))**2
rms = math.sqrt(total/nframes)
print('This is rms: {}'.format(rms))
#Here I tree to find the max amplitude every second. I get an empy list.
i = 0
j = 1
amp_list = [0] #default max
while (i < nframes):
for i in byteList[i:j*framerate]:
if byteList[i+1] >= byteList[i]:
amp_list.pop()
amp_list.append(byteList[i+1])
j+=1
i+=framerate
By default, astype
is not done in-place, instead use:
byteList = byteList.astype(np.float)
In some situations, astype
can be done in-place (see the docs) when keyword copy=True
, but even when done in-place, it returns the array, so the above form can be used.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.