AI Logic

Audio Features and Front-ends

MFCC

Updated:

MFCC computation flow. The left shows the pipeline from the audio waveform through pre-emphasis (optional), framing and windowing, FFT, mel filter bank, logarithm, and DCT to the MFCCs; the right shows the mel-scale curve and 20 triangular mel filters spread over 0–8000 Hz

Background and overview

MFCCs (Mel-Frequency Cepstral Coefficients) are features that represent the rough shape of the spectrum of each short segment of audio with a dozen or so numbers. They are computed by grouping frequencies on the mel scale to match human hearing, taking the logarithm, and then applying the discrete cosine transform (DCT).

A raw audio waveform is unwieldy data, with as many as 16,000 values per second (at 16 kHz). Converting it to MFCCs yields about 13 numbers every 10 ms, which not only shrinks the data but also preserves the information relevant to which phoneme is being spoken (the positions of spectral peaks determined by the shape of the vocal tract).

MFCCs were popularized by a 1980 paper by Davis and Mermelstein. In monosyllabic word recognition, they compared MFCCs, linear-frequency cepstra, linear prediction coefficients and other representations under the same conditions, and 10 MFCCs computed every 6.4 ms gave the best results (96.5% and 95.0% for the two speakers). Since then, MFCCs have long served as the standard feature for speech and speaker recognition.

Computation steps

MFCCs are computed in the following steps (the flow on the left of the figure at the top of the article).

  1. Pre-emphasis (optional): boost high frequencies with y[n]=x[n]−α x[n−1]y[n] = x[n] - \alpha\, x[n-1].
    • Speech has less energy at higher frequencies, and this compensates for it. A common value for α\alpha is 0.97. This step is not in the original paper but is often added in later implementations.
  2. Split into frames and apply a window: divide the waveform into short, slightly overlapping segments (frames) and apply a window such as the Hamming window.
    • The original paper applied a 256-point (25.6 ms) Hamming window to 10 kHz audio, shifting it by 64 points (6.4 ms) or 128 points (12.8 ms). Today a 25 ms window shifted by 10 ms is a common setting.
  3. Compute the power spectrum with the FFT: for each frame, obtain the strength at each frequency.
  4. Apply the mel filter bank: arrange triangular filters and take a weighted sum of the strength within each filter's range.
    • The filters are spaced evenly on the mel scale, so they are narrow at low frequencies and wide at high frequencies. The original paper used 20 filters, spaced linearly up to 1000 Hz and logarithmically above that.
  5. Take the logarithm: take the log of each filter output.
    • Humans perceive loudness roughly logarithmically. In addition, components combined by multiplication (the source that produces the pitch of the voice and the shape of the vocal tract) become additive.
  6. Apply the DCT (discrete cosine transform) and keep only the low-order coefficients: compute the coefficients from the log filter outputs XkX_k with the following formula.
ci=∑k=1KXkcos⁡ ⁣[ i(k−12)πK],i=1,2,…,Mc_i = \sum_{k=1}^{K} X_k \cos\!\left[\, i \left(k - \frac{1}{2}\right) \frac{\pi}{K} \right], \qquad i = 1, 2, \dots, M

Here KK is the number of filters (20 in the original paper), XkX_k is the log of the output of the kk-th filter, MM is the number of coefficients kept, and cic_i is the ii-th MFCC.

The following formula is commonly used to convert to the mel scale.

m=2595log⁡10 ⁣(1+f700)m = 2595 \log_{10}\!\left(1 + \frac{f}{700}\right)

ff is the frequency (Hz) and mm is in mels. 1000 Hz maps to roughly 1000 mels, and above that, mels increase only slowly as frequency rises (the curve at the upper right of the figure).

Why apply the DCT?

The final DCT serves two purposes.

  • Extract only the rough shape of the spectrum: low-order DCT coefficients represent slow variations in the spectrum (peak positions and overall tilt), while high-order coefficients represent fine ripples. What matters for distinguishing phonemes is the peak positions determined by the shape of the vocal tract (formants), so keeping only the low orders is enough. Most of the fine ripples come from the pitch of the voice and have little to do with what is being said.
  • Reduce correlation between coefficients: outputs of neighboring mel filters have very similar values. The DCT turns them into coefficients with little mutual correlation, which works well with distance computations and with statistical models that assume diagonal covariance (such as Gaussian mixture models).

The original paper justifies the cosine transform by noting that the axes obtained in earlier work (Pols's principal component analysis of filter outputs) closely resembled a sequence of cosines. It also reports that the first six or so coefficients capture most of the necessary information.

"Cepstrum" is a coined word formed by reversing the first four letters of "spectrum", and refers to "a frequency analysis applied once more to the log of the spectrum". The MFCC order is easiest to understand as representing the "degree of smoothness" of the spectral shape, rather than time or frequency.

Common settings and caveats

Common settings in practice are as follows.

ItemCommon settingPurpose
Number of coefficients12–13 (including the 0th coefficient or the frame energy)Keep only the rough shape of the spectrum
Delta (Δ) and delta-delta (ΔΔ)Append temporal differences of the coefficients, e.g. for 39 dimensionsCapture how quickly the sound changes
Cepstral mean normalization (CMN)Subtract the mean of each coefficient per utteranceReduce differences due to microphones and room acoustics
Number of mel filtersAbout 20–40Set the frequency resolution

The exact definition of MFCCs differs between libraries: the mel-scale formula (the one above, or Slaney's formula, which is linear below 1000 Hz), how the logarithm is taken (natural log or dB), DCT normalization, the number of filters, and so on. The same audio can produce different values, so use the same library and settings for training and inference, and match the settings when comparing with results in papers.

Comparison with mel spectrograms and current usage

Since deep learning became widespread, it has become more common to feed the mel spectrogram that precedes the MFCC (the log filter outputs from step 5) directly into the model, because the model can learn to use the information that the DCT would otherwise discard. For example, Whisper takes log-mel spectrograms as input. There are also methods that learn features directly from the waveform.

InputDimensions (per frame)StrengthsWeaknessesMain uses
MFCCAbout 13–39Compact, with low correlation between coefficients. Easy to handle even with little dataDiscards fine spectral information. Sensitive to noiseSpeech recognition with Gaussian mixture models and hidden Markov models, speaker recognition, small models
Log-mel spectrogramAbout 40–128Rich in information and can be processed with convolutions like an imageHigh-dimensional, with strong correlation between neighborsDeep-learning speech recognition, speech synthesis, acoustic event detection
Features learned from the waveformModel-dependentEven the filters can be learned to fit the dataTraining requires a lot of data and computewav2vec 2.0, SincNet, LEAF

Because MFCCs are cheap to compute and stable even with little data, they are still used for speaker recognition, lightweight audio processing, and as a baseline for comparison with deep-learning results. Another way to tame the magnitude variation of mel spectrograms is PCEN, which is used in place of the logarithm.

PyTorch example

Show code
python
import math
import torch
import torchaudio

'''
Compute MFCCs from an audio waveform (using torchaudio)
'''

sample_rate = 16000

# As an example, create one second of sound (sum of 440 Hz and 1200 Hz sine waves). In practice, load an audio file with torchaudio.load
t = torch.arange(sample_rate) / sample_rate
waveform = (0.6 * torch.sin(2 * math.pi * 440 * t) + 0.3 * torch.sin(2 * math.pi * 1200 * t)).unsqueeze(0)  # [1, 16000]

# 1. Pre-emphasis (optional): y[n] = x[n] - 0.97 x[n-1]
pre = torch.cat([waveform[:, :1], waveform[:, 1:] - 0.97 * waveform[:, :-1]], dim=1)

# 2-6. Framing, windowing, FFT, mel filter bank, logarithm and DCT in one step
mfcc_transform = torchaudio.transforms.MFCC(
  sample_rate=sample_rate,
  n_mfcc=13,              # number of coefficients to keep
  log_mels=True,          # take the natural log instead of dB
  melkwargs={
    'n_fft': 400,         # 25 ms window (400 points at 16 kHz)
    'hop_length': 160,    # shift by 10 ms
    'n_mels': 40,         # number of mel filters
    'window_fn': torch.hamming_window,
  },
)
mfcc = mfcc_transform(pre)
print(mfcc.shape)  # torch.Size([1, 13, 101])  [channels, coefficients, frames]

# Append temporal changes (deltas) to get a 26-dimensional feature per frame
delta = torchaudio.functional.compute_deltas(mfcc)
features = torch.cat([mfcc, delta], dim=1)
print(features.shape)  # torch.Size([1, 26, 101])

# Subtract the mean of each coefficient per utterance (cepstral mean normalization) to reduce differences in recording conditions
features = features - features.mean(dim=-1, keepdim=True)

FAQ

Q. How many MFCC coefficients should be used?
A.

In speech recognition, 12–13 coefficients plus deltas and delta-deltas, for 39 dimensions in total, are common. The original paper reports that the first six or so capture most of the necessary information.

Q. Should MFCCs or mel spectrograms be used?
A.

When training a deep-learning model on plenty of data, the information-rich log-mel spectrogram is the usual choice. When data is scarce, or when using small models or statistical models, MFCCs, being low-dimensional and weakly correlated, are easier to work with.

Q. Can MFCCs be used for music?
A.

Yes. Because they capture differences in timbre, they have been used for instrument identification and genre classification. However, they discard almost all pitch information, so other features such as the CQT are better suited to handling melodies and chords.

References

  1. Davis, S. B., & Mermelstein, P. (1980). Comparison of parametric representations for monosyllabic word recognition in continuously spoken sentences. IEEE Transactions on Acoustics, Speech, and Signal Processing, 28(4), 357–366.
  2. O'Shaughnessy, D. (1987). Speech Communication: Human and Machine. Addison-Wesley. (Mel-scale formula m = 2595 log10(1 + f/700))
  3. torchaudio.transforms.MFCC (PyTorch documentation).