DEV Community

How an AI Voice Detector Works: Features, Classifiers and a Toy Python Example

By Tania Alwan

Cloned and synthetic voices are now easy to make, so "is this voice real?" has become a practical question for podcasters, journalists, call centres and musicians. An AI voice detector tries to answer it automatically.

This post explains how these detectors work under the hood, what the research community uses to test them, where they fail, and then builds a deliberately tiny detector in Python so you can see the moving parts.

Spoiler: the toy works on toy data. Real detection is much harder, and I will be explicit about why.

What an AI voice detector is actually trying to do

In research, this problem is usually called spoofing detection or anti-spoofing, and the detector is a countermeasure (CM).

The task is binary classification:

  • Bona fide: speech recorded from a real human
  • Spoof: speech produced by text-to-speech (TTS), voice conversion (VC), or a replay of a recording

The detector outputs a score, and a threshold turns the score into a decision. Because false alarms and misses both matter, the field reports the equal error rate (EER): the operating point where the false-acceptance rate equals the false-rejection rate. Lower is better.

The benchmark behind most research: ASVspoof

Most published AI voice detector work is evaluated on data from the ASVspoof challenge series, which started in 2015 and was built to protect automatic speaker verification (ASV) systems.

ASVspoof 2019 introduced a large database with a logical access scenario (TTS and VC attacks) and a physical access scenario (replay). It is described in Wang et al., "ASVspoof 2019: A large-scale public database of synthesized, converted and replayed speech".

ASVspoof 5 moved to crowdsourced data, more modern attacks and adversarial attacks: Wang et al., 2024.

Alongside EER, ASVspoof also uses the tandem detection cost function (t-DCF), which measures how a countermeasure affects a speaker verification system it protects.

Features: what the detector looks at

Synthetic speech can sound convincing to people while still leaving statistical traces in the signal. Classic pipelines start with hand-crafted spectral features:

  • LFCC (linear-frequency cepstral coefficients) and CQCC (constant-Q cepstral coefficients). CQCC, proposed by Todisco, Delgado and Evans, uses a constant-Q transform that gives finer frequency resolution at low frequencies and finer time resolution at high frequencies. LFCC and CQCC front ends paired with Gaussian mixture models (GMMs) were baseline systems in ASVspoof 2019.
  • Log spectrograms and constant-Q spectrograms fed directly into neural networks.
  • Simple descriptors such as spectral centroid, flatness, high-frequency energy and frame-to-frame spectral change. These are useful for intuition, but rarely strong on their own.

Why high frequencies? Many speech generation pipelines work at limited sample rates or use vocoders whose artefacts show up in particular bands. But this is a property of specific systems, not a law of nature, and it changes with every new generator.

Classifiers: from GMMs to graph attention

Detectors broadly fall into two families:

  • Feature + classifier. Extract LFCC or CQCC, then score with GMMs, SVMs or a neural network. Simple and interpretable.
  • End-to-end models that learn directly from audio. RawNet2 for anti-spoofing (Tak et al.) works on the raw waveform, and AASIST (Jung et al.) uses graph attention across spectral and temporal information. Both are widely used reference systems in recent anti-spoofing work.

Commercial "AI voice detector" products generally do not publish their architectures or training data, so treat their accuracy claims with care unless they come with an independent evaluation.

The limitations you should know about

This is the most important section.

  • Generalisation is the weak spot. MΓΌller et al., "Does Audio Deepfake Detection Generalize?" (Interspeech 2022) re-implemented published detectors and tested them on a new dataset of real-world recordings of public figures. Models that looked strong on ASVspoof performed far worse on this in-the-wild data. A detector trained on yesterday's generators may miss tomorrow's.
  • Channel effects confuse models. Compression, phone lines, background noise, reverb and re-recording can change exactly the cues detectors rely on.
  • Adversarial attacks exist. Attackers can deliberately perturb audio to fool a known detector, which is one reason ASVspoof 5 added adversarial attacks.
  • Scores are probabilities, not verdicts. A single detector score should not be treated as proof that a recording is fake or real.

Because detection after the fact is fragile, researchers also work on watermarking synthetic audio at generation time, for example AudioSeal (San Roman et al.). That only helps when the generator cooperates, so the two approaches complement each other.

A toy AI voice detector in Python

The script below generates its own fake "voices" (harmonic tones plus breath-like noise) so it runs without downloading any dataset. "Synthetic" clips get a steadier pitch and a band-limited noise floor, a crude stand-in for vocoder artefacts. It extracts eight summary features (mean and standard deviation of four descriptors) from a short-time Fourier transform and trains a logistic regression.

This is a toy. It detects the artefacts I planted. It says nothing about real cloned voices.

pip install numpy scikit-learn
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve
SR = 16000
rng = np.random.default_rng(0)
def fake_voice(synthetic, dur = 1.0, cutoff = 4000):
    """Toy 'voice': a harmonic tone plus breath noise. 'Bona fide' clips get pitch jitter and full-band noise; 'synthetic' clips get a steadier pitch and a band-limited noise floor (a crude stand-in for vocoder artefacts). Not real speech!"""
    t = np.arange(int(SR * dur)) / SR
    f0 = rng.uniform(100, 220)
    jitter = 0.002 if synthetic else 0.02
    f0_track = f0 * (1 + jitter * np.cumsum(rng.standard_normal(t.size)) / np.sqrt(t.size))
    phase = 2 * np.pi * np.cumsum(f0_track) / SR
    y = sum(np.sin(k * phase) / k for k in range(1, 30))
    noise = rng.standard_normal(t.size) * 0.05
    if synthetic:
        # remove most energy above `cutoff` Hz from the noise floor
        spec = np.fft.rfft(noise)
        spec[int(cutoff * t.size / SR):] *= 0.1
        noise = np.fft.irfft(spec, n = t.size)
    return (y + noise) / np.max(np.abs(y + noise))
def features(y, n_fft = 512, hop = 256):
    frames = np.lib.stride_tricks.sliding_window_view(y, n_fft)[::hop]
    mag = np.abs(np.fft.rfft(frames * np.hanning(n_fft), axis = 1)) + 1e-10
    freqs = np.fft.rfftfreq(n_fft, 1 / SR)
    log_spec = np.log(mag)
    centroid = (mag * freqs).sum(1) / mag.sum(1)
    flatness = np.exp(log_spec.mean(1)) / mag.mean(1)
    hf_ratio = mag[:, freqs > 4000].sum(1) / mag.sum(1)
    flux = np.r_[0, np.sqrt((np.diff(log_spec, axis = 0) ** 2).mean(1))]
    feats = [centroid / 1000, flatness, hf_ratio, flux]
    return np.array([f(x) for x in feats for f in (np.mean, np.std)])
labels = np.array([0] * 200 + [1] * 200) # 0 = bona fide, 1 = synthetic
X = np.array([features(fake_voice(bool(l))) for l in labels])
X_tr, X_te, y_tr, y_te = train_test_split(X, labels, test_size = 0.3, random_state = 0, stratify = labels)
clf = LogisticRegression(max_iter = 1000).fit(X_tr, y_tr)
scores = clf.predict_proba(X_te)[:, 1]
fpr, tpr, _ = roc_curve(y_te, scores)
i = np.nanargmin(np.abs(fpr - (1 - tpr)))
print(f"accuracy: {clf.score(X_te, y_te):.2f}")
print(f"EER: {(fpr[i] + 1 - tpr[i]) / 2:.3f}")
# A "new generator": same idea, different artefact (cutoff at 7 kHz)
X_new = np.array([features(fake_voice(bool(l), cutoff = 7000)) for l in labels])
print(f"accuracy on unseen 'generator': {clf.score(X_new, labels):.2f}")

With these seeds, my run printed: accuracy: 0.95, EER: 0.083, accuracy on unseen 'generator': 0.72. Your numbers may differ slightly with other library versions.

The last line is the interesting one: the same classifier, tested on "synthetic" clips whose artefact sits at 7 kHz instead of 4 kHz, drops sharply. That is the generalisation problem from the research above, in miniature.

Things worth trying:

  • Plot the per-feature coefficients (clf.coef_) to see which cues the model leans on.
  • Add the 7 kHz clips to the training set and check whether a third, different artefact still fools it.
  • Swap the synthetic data for a real dataset such as ASVspoof 2019 LA and a proper front end (LFCC or a log spectrogram), and you will quickly see why the field moved to deep models.

Takeaways

  • An AI voice detector is a binary classifier scoring bona fide versus spoofed speech, usually evaluated with EER
  • Features range from LFCC and CQCC to raw waveforms; models range from GMMs to RawNet2 and AASIST
  • Detectors generalise poorly to unseen generators and real-world audio, so treat any single score with caution

If you build or use voice-cloning tools, detection is only half the story. Consent matters too: platforms such as Voicestars let people create AI versions of their own voice, and clear consent rules are part of making synthetic voices trustworthy.

Disclosure: this article was written in partnership with Voicestars.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.