python实现MFCC计算
时间: 2024-01-10 18:03:31 浏览: 28
MFCC(Mel Frequency Cepstral Coefficients)是一种常用于语音识别和音频处理的特征提取方法,可以将音频信号转化为一组能够描述其特征的系数。以下是Python实现MFCC计算的示例代码:
```python
import librosa
import numpy as np
# Load audio file
y, sr = librosa.load('audio.wav', sr=16000)
# Pre-emphasis
pre_emphasis = 0.97
emphasized_signal = np.append(y[0], y[1:] - pre_emphasis * y[:-1])
# Framing
frame_size = 0.025 # 25ms
frame_stride = 0.01 # 10ms
frame_length, frame_step = frame_size * sr, frame_stride * sr
signal_length = len(emphasized_signal)
frame_length = int(round(frame_length))
frame_step = int(round(frame_step))
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)]
# Windowing
frames *= np.hamming(frame_length)
# Fourier Transform and Power Spectrum
NFFT = 512
mag_frames = np.absolute(np.fft.rfft(frames, NFFT)) # Magnitude of the FFT
pow_frames = ((1.0 / NFFT) * ((mag_frames) ** 2)) # Power Spectrum
# Filter Banks
nfilt = 40
low_freq_mel = 0
high_freq_mel = (2595 * np.log10(1 + (sr / 2) / 700)) # Convert Hz to Mel
mel_points = np.linspace(low_freq_mel, high_freq_mel, nfilt + 2) # Equally spaced in Mel scale
hz_points = (700 * (10 ** (mel_points / 2595) - 1)) # Convert Mel to Hz
bin = np.floor((NFFT + 1) * hz_points / sr)
fbank = np.zeros((nfilt, int(np.floor(NFFT / 2 + 1))))
for m in range(1, nfilt + 1):
f_m_minus = int(bin[m - 1]) # left
f_m = int(bin[m]) # center
f_m_plus = int(bin[m + 1]) # right
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])
# Apply filter banks
filter_banks = np.dot(pow_frames, fbank.T)
filter_banks = np.where(filter_banks == 0, np.finfo(float).eps, filter_banks) # Numerical Stability
filter_banks = 20 * np.log10(filter_banks) # dB
# MFCCs
num_ceps = 12
mfcc = dct(filter_banks, type=2, axis=1, norm='ortho')[:, 1 : (num_ceps + 1)]
# Mean normalization
mfcc -= (np.mean(mfcc, axis=0) + 1e-8)
print(mfcc)
```
这里使用了Librosa库来加载音频文件和进行预加重,以及进行帧划分、加窗、傅里叶变换、滤波器组应用和离散余弦变换等步骤。最后,对MFCC系数进行均值归一化。