以备不时之需

频率和振幅

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import pylab as pl
import numpy as np
from scipy.io import wavfile

sampFreq, snd = wavfile.read('test.wav')
snd = snd / (2. ** 15)
s1 = snd # [:,0] 双声道
n = len(s1)
p = pl.fft(s1)
nUniquePts = int(np.ceil((n + 1) / 2.0))
p = p[0:nUniquePts]
p = abs(p)
p = p / float(n)
p = p ** 2
if n % 2 > 0:
p[1:len(p)] = p[1:len(p)] * 2
else:
p[1:len(p) - 1] = p[1:len(p) - 1] * 2

freqArray = pl.arange(0, nUniquePts, 1.0) * (sampFreq / n)
y = 10 * np.log10(p)
pl.plot(freqArray,y, linewidth=1, color=color)
pl.show()

波形图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
f = wave.open(filename, "rb")
# 读取格式信息
# (nchannels, sampwidth, framerate, nframes, comptype, compname)
# 声道数, 量化位数(byte单位), 采样频率, 采样点数, 压缩类型, 压缩类型的描述
params = f.getparams()
nchannels, sampwidth, framerate, nframes = params[:4]

# 读取波形数据
str_data = f.readframes(nframes)
f.close()

# 将波形数据转换为数组
wave_data = np.frombuffer(str_data, dtype=np.short)
time = np.arange(0, nframes) * (1.0 / framerate)
if nchannels == 2:
wave_data.shape = -1, 2
# transpose
wave_data = wave_data.T
# 绘制波形
pl.subplot(211)
pl.plot(time, wave_data[0])
pl.subplot(212)
pl.plot(time, wave_data[1], c="g")
else:
pl.subplot(211)
pl.plot(time, wave_data)
pl.subplot(212)
pl.specgram(wave_data, 1024, framerate)
# pl.subplot(212)
# nf = np.fft.fft(wave_data)
# pl.plot(time,nf)
pl.show()