problem
I found many places on the Internet, and the core code is the same, such as this sentence.
wavedata=np.fromstring(bindata,dtype=np.short)
The effect is also OK.
But a random audio file in office was loaded at one time, and the waveform was completely wrong. It was close to the square wave, and it was all numbers with ups and downs.
The waveform parameters are as follows:
_wave_params(nchannels=1, sampwidth=1, framerate=11025, nframes=……)
Look at its sampling quantization bit width(sampwidth)It’s only 1 byte. It’s obviously wrong to use numpy.short (int16) and byte/int8.
Load it into the audio processing software, and the displayed information is unsigned 8 bits, thenFor this wav, withuint8Is the positive solution.
In addition, in drawing, we also encounter the problems of sub drawing segmentation, color, general drawing title and window title.
Integrate other search results and try by yourself,Especially with reference to this blog post, the drawing parameters are very detailed!
resolvent
The following simple code is written to automatically process the quantization bit width, title, number of channels and number of waveform subgraphs.
# -*- coding: utf-8 -*-
import wave
import numpy as np
import pylab as pl
#fPath=r"C:\Program Files\Microsoft Office\root\Office16\MEDIA\CAMERA.WAV"
fPath=r"C:\Windows\Media\Alarm04.wav"
f=wave.open(fPath,"rb")
para=f.getparams()
bindata=f.readframes(para.nframes)
f.close()
#The data type is determined by the quantized digits, which cannot be all short, int16
#INT0 is purely occupied, and more than 16 bits are not listed temporarily. Because 24 bit quantization cannot be processed directly, there is no numpy.int24, which needs to be customized. It will be explained at the beginning or find an online solution
dtypes=[np.int0,np.uint8,np.int16]
#The new version of Python prompt.Fromstring() is obsolete and is not recommended
wavedata=np.frombuffer(bindata,dtype=dtypes[para.sampwidth])
wavedata.shape = -1,para.nchannels
Time=np.arange (0, para.nframes) * (1.0/para.framerate) # turns to seconds
pColors="bgrcmykw"
wTitle="Wave forms"
Pl.figure (wtitle) # window custom initialization, such as title, etc
#Set the overall title of the drawing, plus the file name; Non windows needs to modify the separator
pl.suptitle(wTitle+" of " + fPath.split('\\')[-1])
for i in range(para.nchannels):
pl.subplot(para.nchannels*100+10+i+1)
pl.plot(time,wavedata[:,i],pColors[i])
pl.xlabel("Time(seconds)")
pl.show()