AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
♪Audio & Speech AI
  1. Audio Basics: From Sound Waves to Spectrograms
  2. Speech Recognition: CTC, wav2vec 2.0 and Whisper
  3. Speech Synthesis: From Text to a Natural Voice
  4. Music & Audio Generation: Codecs, Tokens and Diffusion
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Audio & Speech AI

Speech Synthesis: From Text to a Natural Voice

The text-to-speech pipeline (text frontend → acoustic model → vocoder), the landmark models WaveNet, Tacotron 2, HiFi-GAN and VITS, how TTS is evaluated, and the ethics of voice cloning.

Intermediate~24 min·6 references
Key terms
Text-to-speech (TTS)VocoderWaveNetMel spectrogramGenerative adversarial network (GAN)Variational autoencoder (VAE)

Text-to-speech (TTS) reads text aloud: screen readers for blind users, GPS directions, audiobooks, IVR phone menus, dubbing, and the voice of AI assistants. Early systems glued together recorded snippets (concatenative synthesis) or used hand-built signal models, and sounded robotic. Since 2016, neural TTS has reached the point where listeners often cannot tell synthetic speech from a recording — which is exactly why this lesson ends with ethics.

≈
Analogy: a news anchor, a conductor and an instrument
First, a news anchor reads the script and decides how to *say* “Rp15.000” (“lima belas ribu rupiah”). Then a conductor plans the performance: which sound comes when, how long, how high — that plan is the mel spectrogram. Finally, an instrument turns the plan into actual air vibrations — that is the Vocoder. Neural TTS replaces each role with a network (or merges them into one).

The classic two-stage neural pipeline

  1. Text normalisation — expand numbers, dates, currencies and abbreviations: “Jl. Sudirman No. 5, 17/8” → “jalan sudirman nomor lima, tujuh belas agustus”. Rule-based or learned; errors here are the most common audible TTS bug.
  2. Grapheme-to-phoneme (G2P) — convert letters to phonemes, e.g. to distinguish the two “e” sounds in Indonesian “*sepak*” vs “*enak*”. Some models skip this and learn directly from characters.
  3. Acoustic model — predicts a Mel spectrogram from the phoneme sequence, deciding duration, pitch (prosody) and timbre.
  4. Vocoder — converts the mel spectrogram into a waveform, reconstructing the phase information the spectrogram threw away.
Loading interactive…
The classic pipeline as a diagram. Walk through it from raw text to waveform, and tap Pre-net to see the autoregressive loop inside Tacotron 2. Notice the mel spectrogram hand-off in the middle, and how VITS (bottom) skips it entirely.

WaveNet: generating audio one sample at a time

WaveNet (van den Oord et al., 2016)[1] models raw audio autoregressively: each sample is predicted from all previous ones. To see far into the past cheaply, it stacks dilated causal convolutions with dilations 1, 2, 4, …, 512, so 10 layers already cover 1,024 past samples. Each sample is μ-law companded to 256 levels and predicted with a Softmax — a classification over amplitudes. WaveNet cut the gap to human speech in listening tests by over 50%, but generating 16,000+ samples per second sequentially was far too slow for production at first.

p(x) = Πₜ p(xₜ | x₁, …, xₜ₋₁) f(x) = sign(x) · ln(1 + μ|x|) / ln(1 + μ), μ = 255
Autoregressive factorisation, and μ-law companding that gives quiet samples finer resolution than loud ones.
In words: Left: the probability of a whole waveform is split into a chain of “next sample given all previous samples” predictions — exactly what WaveNet's causal convolutions compute. Right: μ-law companding squeezes the amplitude range logarithmically before quantizing to 256 levels, so quiet sounds get many levels and loud sounds fewer.
Symbols(hover a symbol in the formula)
p(x)
probability of the entire waveform x = (x₁, …, x_T)
Πₜ
product over all time steps t
p(xₜ | x₁, …, xₜ₋₁)
probability of sample t given all earlier samples (a softmax over 256 levels)
xₜ
the audio sample at time t, scaled to [−1, 1]
f(x)
the companded value, still in [−1, 1], then quantized to 256 levels
sign(x)
+1 for positive x, −1 for negative x (keeps the sign)
ln
natural logarithm
|x|
absolute value of the sample
μ
mu, the compression strength; 255 gives 256 levels
▸Worked example
Chain rule, 3 samples: p(x₁) = 0.5, p(x₂ | x₁) = 0.4, p(x₃ | x₁, x₂) = 0.9 p(x) = 0.5 × 0.4 × 0.9 = 0.18 μ-law with μ = 255 (ln 256 = 5.545): x = 0.01: ln(1 + 2.55) / 5.545 = 1.267 / 5.545 = 0.228 → level round((0.228 + 1)/2 · 255) = 157 x = 0.1: ln(26.5) / 5.545 = 0.591 → level 203 x = 0.5: ln(128.5) / 5.545 = 0.876 → level 239 → 0.01 → 0.1 spans 46 levels, 0.1 → 0.5 only 36: quiet detail is preserved.
Loading interactive…
Dilated causal convolutions. Walk through steps 1–5 to watch the receptive field of the newest output grow 2 → 4 → 8 → 16 samples with only 4 layers; every arrow points from the past, never the future. Then tap tanh, σ and ⊙ in the right panel to see the gated activation, residual and skip paths inside each layer.

Tacotron 2: text → mel → WaveNet

Tacotron 2 (Shen et al., 2018)[2] is a Seq2seq (sequence-to-sequence) model with Attention: a character encoder, and an autoregressive decoder that outputs 80-band mel frames one step at a time, attending to the right part of the text. A modified WaveNet then acts as the vocoder. It reached a mean opinion score (MOS) of 4.53, close to 4.58 for professionally recorded speech. Its weakness is attention: on long or unusual inputs it may skip, repeat or babble — which motivated non-autoregressive models (FastSpeech family) that predict an explicit duration for every phoneme and generate all frames in parallel.

HiFi-GAN: fast, high-quality vocoding

HiFi-GAN (Kong et al., 2020)[3] made vocoders fast enough for everyday use. A fully convolutional generator upsamples the mel spectrogram to a waveform in one parallel pass, trained as a GAN against two kinds of discriminators: multi-period (looks at samples spaced 2, 3, 5, 7, 11 apart to catch periodic pitch patterns) and multi-scale (looks at the waveform at several resolutions). Extra losses — L1 on the mel spectrogram and feature matching — stabilise training. It runs many times faster than real time on a GPU and is usable on CPU, with quality comparable to autoregressive WaveNet.

VITS: one end-to-end model

VITS (Kim et al., 2021)[4] merges acoustic model and vocoder into a single network trained end to end. It is a conditional VAE whose latent is shaped by a normalizing flow, whose decoder is a HiFi-GAN-style generator trained adversarially, with monotonic alignment search to learn text–audio alignment without an external aligner and a stochastic duration predictor so the same sentence can be spoken with different rhythms. Meta's MMS-TTS models, covering over a thousand languages including Indonesian, use the VITS architecture.

ModelRoleKey ideaSpeed
WaveNet (2016)Vocoder / raw audio modelDilated causal convs, sample-level autoregressionVery slow (sequential)
Tacotron 2 (2018)Acoustic modelSeq2seq + attention → mel framesModerate (frame-level autoregression)
HiFi-GAN (2020)VocoderGAN with multi-period + multi-scale discriminatorsFast (parallel)
VITS (2021)End-to-end TTSVAE + flow + adversarial training + duration predictorFast (parallel)
VALL-E (2023)Zero-shot TTSLanguage model over neural codec tokens, 3 s voice promptModerate (token autoregression)

How TTS is evaluated

  • MOS (Mean Opinion Score) — listeners rate naturalness from 1 (bad) to 5 (excellent); report the mean with a confidence interval. Still the gold standard, but expensive and hard to compare across studies.
  • Intelligibility — run an ASR model on the synthesized audio and compute WER/CER against the input text. Catches skipped or mispronounced words.
  • Speaker similarity — cosine similarity between speaker-verification embeddings of the reference and generated voice (for cloning).
  • Real-time factor (RTF) — synthesis time ÷ audio duration; RTF < 1 means faster than real time.

Voice cloning and zero-shot TTS

Multi-speaker TTS conditions the model on a speaker embedding. Zero-shot systems go further: VALL-E (Wang et al., 2023)[5] treats TTS as language modelling over discrete tokens of a neural Neural audio codec, and can imitate a voice — including its emotion and room acoustics — from a 3-second recording. That capability is powerful for accessibility (restoring the voice of someone with ALS from old recordings) and dubbing, but it is also the engine of voice-phishing scams and political deepfakes.

!
Voice cloning ethics — minimum standards
Consent: only clone a voice with the speaker's explicit, informed, revocable permission; voice is biometric personal data under laws like Indonesia's UU PDP and the EU GDPR. Disclosure: tell listeners the audio is synthetic. Provenance: add watermarks or content credentials where possible and keep logs. Misuse defences: families and companies should agree on verification phrases — scammers already clone a relative's voice from social-media clips to ask for urgent transfers. Release policy: many labs have withheld zero-shot cloning models precisely because of these risks.

The knobs

knobspeaking_rate / length_scale
What it is
Scales predicted phoneme durations (length_scale = 1 / speaking_rate). Available in duration-based models (FastSpeech, VITS).
↑ If you increase it
Higher speaking_rate → faster, shorter audio; beyond ~1.5 consonants get swallowed and intelligibility drops.
↓ If you decrease it
Slower, clearer speech (good for learners and announcements); too slow sounds drawn-out and unnatural.
Typical values
0.8–1.3; 1.0 by default.
knobnoise_scale
What it is
Standard deviation of the random latent sampled from the prior in VITS-style models; controls variation in pitch and timbre.
↑ If you increase it
More expressive, varied intonation; too high gives wobbly pitch and artifacts.
↓ If you decrease it
Stable but flat, monotone delivery; every run sounds the same.
Typical values
≈ 0.667 (VITS default).
knobnoise_scale_duration
What it is
Noise fed to the stochastic duration predictor in VITS; controls rhythm variation.
↑ If you increase it
More natural, varied timing between runs; too high produces odd pauses and rushed words.
↓ If you decrease it
Metronome-like, predictable rhythm.
Typical values
≈ 0.8 (VITS default).
knobreference audio length (cloning)
What it is
Duration of the voice sample used to condition a multi-speaker or zero-shot model.
↑ If you increase it
Better speaker similarity and accent capture, up to a point (~10–30 s); also copies background noise and room echo.
↓ If you decrease it
Easier to obtain (which is the danger), but timbre and accent are matched less reliably.
Typical values
3–30 s of clean, single-speaker audio — always with consent.

In code: VITS-based Indonesian TTS

python
import torch, scipy.io.wavfile
from transformers import VitsModel, AutoTokenizer

name = "facebook/mms-tts-ind"   # MMS-TTS Indonesian (VITS architecture)
tokenizer = AutoTokenizer.from_pretrained(name)
model = VitsModel.from_pretrained(name, speaking_rate=1.0,
                                  noise_scale=0.667, noise_scale_duration=0.8)

text = "selamat pagi, hari ini kita belajar tentang sintesis suara"
inputs = tokenizer(text, return_tensors="pt")

torch.manual_seed(0)                      # VITS is stochastic: fix the seed
with torch.no_grad():
    wav = model(**inputs).waveform[0]     # float waveform

scipy.io.wavfile.write("tts.wav", rate=model.config.sampling_rate, data=wav.numpy())
Write numbers as words before synthesis — MMS models expect normalised, lower-case text. See the VITS model docs for all options[6].
✓
Common pitfalls
Mismatched features: a vocoder trained on mels with one sample rate / n_fft / n_mels produces buzzing noise on mels made with other settings. Unnormalised text: “2025” or “dr.” read letter by letter. Out-of-domain text: a model trained on news reads chat slang or English loanwords badly. Data quality: a few hours of clean, consistent single-speaker studio audio beats many hours of noisy recordings.
▸Go deeper: normalizing flows and monotonic alignment

A normalizing flow is a stack of invertible transformations with tractable Jacobians. In VITS it maps a simple text-conditioned Gaussian into the complex distribution of audio latents, making the prior expressive enough that samples sound natural. Because flows are invertible, the same network is used in both directions during training and inference.

Monotonic alignment search exploits the fact that speech follows text left to right without going back: a dynamic-programming search finds the most likely monotonic mapping from text tokens to latent frames, and the durations derived from it supervise the duration predictor. This removes the attention failures (skips, repeats) that plagued Tacotron-style models.

Quiz

1.
In a two-stage neural TTS system, what does the vocoder do?
2.
Why was the original WaveNet too slow for real-time production use?
3.
Your VITS voice sounds flat and identical on every run. Which knob should you raise first?
4.
Which problem of Tacotron 2 motivated duration-based, non-autoregressive TTS?
5.
A client asks you to clone a celebrity's voice from YouTube clips for an ad, without the celebrity's agreement. What is the right response?
Score: 0/5

References

  1. [1]
    WaveNet: A Generative Model for Raw Audio
    Papervan den Oord et al.2016arxiv.org
  2. [2]
    Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions
    PaperShen et al.2018arxiv.org
    Tacotron 2.
  3. [3]
    HiFi-GAN: Generative Adversarial Networks for Efficient and High Fidelity Speech Synthesis
    PaperKong et al.2020arxiv.org
  4. [4]
    Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech
    PaperKim et al.2021arxiv.org
    VITS.
  5. [5]
    Neural Codec Language Models are Zero-Shot Text to Speech Synthesizers
    PaperWang et al.2023arxiv.org
    VALL-E.
  6. [6]
    Hugging Face Transformers — VITS model documentation
    Docshuggingface.co
← Previous
Speech Recognition: CTC, wav2vec 2.0 and Whisper
Next →
Music & Audio Generation: Codecs, Tokens and Diffusion