梅尔频谱系数(MFCC)的完整代码
时间: 2024-05-05 17:12:41 浏览: 122
mfcc.rar_MFCC_梅尔倒谱系数
```python
import numpy as np
import scipy.io.wavfile as wav
from scipy.fftpack import dct
# 读取音频文件
sample_rate, signal = wav.read("audio.wav")
# 预处理音频信号
pre_emphasis = 0.97
emphasized_signal = np.append(signal[0], signal[1:] - pre_emphasis * signal[:-1])
# 分帧
frame_size = 0.025 # 帧大小(秒)
frame_stride = 0.01 # 帧之间的间隔(秒)
frame_length, frame_step = frame_size * sample_rate, frame_stride * sample_rate
signal_length = len(emphasized_signal)
num_frames = int(np.ceil(float(np.abs(signal_length - frame_length)) / frame_step))
pad_signal_length = num_frames * frame_step + frame_length
z = np.zeros((pad_signal_length - signal_length))
pad_signal = np.append(emphasized_signal, z)
indices = np.tile(np.arange(0, frame_length), (num_frames, 1)) + np.tile(
np.arange(0, num_frames * frame_step, frame_step), (frame_length, 1)).T
frames = pad_signal[indices.astype(np.int32, copy=False)]
# 加窗
frames *= np.hamming(frame_length)
# 傅里叶变换
NFFT = 512
mag_frames = np.absolute(np.fft.rfft(frames, NFFT))
# 梅尔滤波器组
nfilt = 40
low_freq_mel = 0
high_freq_mel = (2595 * np.log10(1 + (sample_rate / 2) / 700)) # Hz转换为Mel
mel_points = np.linspace(low_freq_mel, high_freq_mel, nfilt + 2) # 在Mel刻度上均匀分布的点
hz_points = (700 * (10**(mel_points / 2595) - 1)) # Mel转换为Hz
bin = np.floor((NFFT + 1) * hz_points / sample_rate).astype(int)
# 计算滤波器组的增益
fbank = np.zeros((nfilt, int(np.floor(NFFT / 2 + 1))))
for m in range(1, nfilt + 1):
f_m_minus = int(bin[m - 1]) # 左边界
f_m = int(bin[m]) # 中心
f_m_plus = int(bin[m + 1]) # 右边界
for k in range(f_m_minus, f_m):
fbank[m - 1, k] = (k - bin[m - 1]) / (bin[m] - bin[m - 1])
for k in range(f_m, f_m_plus):
fbank[m - 1, k] = (bin[m + 1] - k) / (bin[m + 1] - bin[m])
# 应用滤波器组
filter_banks = np.dot(mag_frames, fbank.T)
filter_banks = np.where(filter_banks == 0, np.finfo(float).eps, filter_banks) # 防止出现log(0)的情况
# 取对数
filter_banks = 20 * np.log10(filter_banks)
# 应用离散余弦变换(DCT)
num_ceps = 12
mfcc = dct(filter_banks, type=2, axis=1, norm='ortho')[:, 1 : (num_ceps + 1)]
# 去除第一项(能量)
mfcc -= (np.mean(mfcc, axis=0) + 1e-8)
# 输出MFCC特征
print(mfcc)
```
阅读全文