MODULE 9  ยท  The Cutting Edge

Voice & TTS: How AI Turns Text Into Human Speech

Close your eyes and listen to someone speak. Not the words โ€” the way they speak. AI is learning to replicate all of that.

๐Ÿ“… Mar 2026
โฑ 10 min read
๐ŸŽฏ Episode 59 of 98
Voice AITTSSpeech SynthesisAudio
In this episode

Close your eyes and listen to someone speak. Not the words โ€” the way they speak. The pause before a punchline. The rising pitch of a question. The warmth when they say your name. The way their voice cracks when they're tired.

Now try to build a machine that does all of that from raw text.

That's Text-to-Speech (TTS) โ€” and it's gone from robotic "PLEASE. LEAVE. A. MESSAGE." to voices so real you genuinely can't tell the difference. ElevenLabs can clone your voice from 30 seconds of audio. OpenAI's real-time voice can hold a conversation with emotional inflection. CosyVoice can generate speech in languages the speaker never spoke.

Here's how it all works.

The Two Sides: STT and TTS

Voice AI has two directions:

Direction Full Name What It Does Key Models

STTSpeech-to-TextAudio โ†’ text (transcription)Whisper, Deepgram, AssemblyAI
TTSText-to-SpeechText โ†’ audio (synthesis)ElevenLabs, OpenAI TTS, CosyVoice

Both are hard, but for completely different reasons. STT needs to handle accents, background noise, multiple speakers, and domain-specific vocabulary. TTS needs to sound human โ€” with proper rhythm, emotion, and naturalness.

โšก

Speech-to-Text: How Whisper Works

snippet
code
Whisper (OpenAI, 2022) is the most widely used STT model. It's open-source, supports 99 languages, and handles noisy audio remarkably well.

Architecture

Whisper is an encoder-decoder transformer โ€” similar to the original transformer from the "Attention Is All You Need" paper:

Audio Waveform

example
code
โ†“

Mel Spectrogram (80 channels ร— time)

example
code
โ†“

Convolutional Stem (2 conv layers)

example
code
โ†“

Transformer Encoder (process audio features)

example
code
โ†“

Transformer Decoder (generate text tokens autoregressively)

example
code
โ†“

Text Output

Step 1: Audio to Spectrogram

Raw audio is a 1D waveform โ€” just amplitude over time. Whisper converts it to a Mel spectrogram โ€” a 2D representation that shows frequency content over time:

Raw audio: [0.1, -0.3, 0.5, -0.2, ...] (16kHz = 16,000 samples/sec)

example
code
โ†“

Mel spectrogram: 80 frequency bins ร— T time frames

example
code
(basically a "heatmap" of sound frequencies)

Think of it like sheet music โ€” the y-axis shows pitch (frequency), the x-axis shows time, and the intensity shows volume. This representation makes it much easier for the model to understand speech.

Step 2: Encode

The encoder processes 30-second audio chunks. Two convolutional layers first downsample the spectrogram, then transformer layers process the sequence:

Input: 80 ร— 3000 (80 Mel bins ร— 30 seconds at 100 frames/sec)

After conv: 1500 ร— d_model

After encoder: 1500 ร— d_model (contextualized audio features)

Step 3: Decode

The decoder generates text tokens one at a time, attending to both previous text tokens and the encoder's audio features. It uses cross-attention โ€” the decoder's queries attend to the encoder's keys and values:

Decoder input: [, , ] Decoder output: "Hello", "how", "are", "you", "today",

Special tokens control behavior:

โ€” language tag โ€” transcription mode (vs for translation) โ€” whether to include timestamps

Whisper Model Sizes

Model Params VRAM Speed (relative) English WER

tiny39M~1GB32x7.6%
base74M~1GB16x5.0%
small244M~2GB6x3.4%
medium769M~5GB2x2.9%
large-v31.5B~10GB1x2.2%
snippet
code
WER = Word Error Rate. Whisper large-v3 gets 97.8% of words correct on English speech โ€” better than many human transcribers.

๐Ÿ”ง

Text-to-Speech: The Modern Pipeline

TTS has evolved through three generations:

Generation 1: Concatenative (1990sโ€“2010s)

Record a voice actor saying thousands of phrases. Chop the recordings into phoneme snippets. Stitch them together for new sentences. Sounded robotic because the stitching was never seamless.

Generation 2: Neural TTS (2016โ€“2022)

Use neural networks to generate speech from scratch. Tacotron (Google, 2017) and WaveNet (DeepMind, 2016) were breakthroughs โ€” they generated mel spectrograms from text, then converted spectrograms to audio waveforms.

Text โ†’ Tacotron (text โ†’ mel spectrogram) โ†’ WaveNet (mel โ†’ audio waveform)

Generation 3: End-to-End Neural (2023+)

Modern TTS models generate audio directly from text using transformer or diffusion architectures, often producing speech indistinguishable from real humans.

๐Ÿ“Š

How Modern TTS Works

Let's break down the pipeline of a state-of-the-art TTS system:

Step 1: Text Processing

Raw text needs normalization before the model sees it:

Input: "Dr. Smith earned $1.5M in Q3 2024"

Normalized: "Doctor Smith earned one point five million dollars in queue three twenty twenty four"

This includes:

Abbreviation expansion (Dr. โ†’ Doctor)

Number verbalization ($1.5M โ†’ one point five million dollars)

Punctuation to prosody cues (commas โ†’ short pauses)

Step 2: Phoneme Conversion

Text gets converted to phonemes โ€” the actual sounds of speech:

"Hello world" โ†’ /h ษ› l oสŠ w ษœห r l d/

This handles the irregularity of English spelling. "Through," "though," "thought," "tough" โ€” four different pronunciations from similar spellings. A grapheme-to-phoneme (G2P) model handles this conversion.

Step 3: Acoustic Model

The core neural network that converts phonemes (+ speaker embedding + emotion embedding) into an audio representation:

Inputs:

Output:

Step 4: Vocoder (Spectrogram โ†’ Audio)

The vocoder converts the mel spectrogram into an actual audio waveform. Modern vocoders include:

Vocoder Speed Quality Notes

WaveNetVery slowExcellentAutoregressive, sample by sample
WaveGlowFastGoodFlow-based, parallel
HiFi-GANVery fastExcellentGAN-based, real-time capable
VocosVery fastExcellentLatest, lightweight

HiFi-GAN is the most popular โ€” it generates audio faster than real-time with near-perfect quality.

Voice Cloning: How ElevenLabs Does It

Voice cloning creates a speaker embedding โ€” a vector that captures everything unique about a voice: pitch, timbre, accent, speaking style, breathiness.

The Process

Reference audio (30 sec) โ†’ Speaker Encoder โ†’ Speaker Embedding [256-dim vector]

example
code
โ†“

New text โ†’ TTS Model + Speaker Embedding โ†’ Cloned speech

The speaker encoder is trained on thousands of voices to extract a compact representation of vocal identity. Once you have this embedding, you can generate any text in that voice.

What the Embedding Captures

Dimension What It Encodes

Pitch range How high/low the voice naturally sits

TimbreThe "color" of the voice โ€” bright, warm, raspy
Speaking rateNatural pace and rhythm
Accent featuresRegional pronunciation patterns
BreathinessHow airy or clear the voice sounds
Vocal fryThat low, creaky quality some voices have

With just 30 seconds of clean audio, modern systems can create a remarkably accurate voice clone. ElevenLabs' "Instant Voice Cloning" works with as little as 1 minute; their "Professional Voice Cloning" uses 30+ minutes for studio-quality results.

๐Ÿ’ก

Real-time Voice: GPT-4o's Approach

GPT-4o's voice mode doesn't use a traditional TTS pipeline. Instead, it generates audio tokens directly:

Traditional: Text โ†’ LLM โ†’ Text response โ†’ TTS โ†’ Audio

GPT-4o: Audio โ†’ LLM โ†’ Audio tokens โ†’ Audio decoder โ†’ Audio

The LLM itself predicts audio tokens โ€” discrete codes from a neural audio codec like EnCodec (Meta). This means:

No text intermediate โ€” the model goes directly from understanding to speaking

Emotional expression โ€” the model can express laughter, hesitation, excitement without explicit programming

Low latency โ€” no waiting for a separate TTS pipeline

Interruption handling โ€” the model can stop mid-sentence and respond to new input

This is why GPT-4o's voice sounds so natural compared to "read text aloud" approaches.

๐Ÿ”ฌ

Neural Audio Codecs: The Foundation

Modern voice AI relies on neural audio codecs โ€” models that compress audio into discrete tokens:

snippet
code
EnCodec (Meta)

Audio waveform โ†’ Encoder โ†’ Residual Vector Quantization โ†’ Discrete tokens

example
code
โ†“
                           Decoder โ† โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€โ”˜
                              โ†“
                        Reconstructed audio

EnCodec compresses audio to as low as 1.5 kbps โ€” that's 10x more compressed than MP3 โ€” while maintaining good speech quality. The discrete tokens are what LLMs learn to predict.

Residual Vector Quantization (RVQ): Instead of one codebook, EnCodec uses 8 codebooks in layers. The first captures coarse structure (pitch, rhythm), each subsequent one adds finer details (timbre, harmonics). It's like painting in layers โ€” rough sketch first, then details.

๐Ÿ›ก๏ธ

CosyVoice: Open-Source Voice Cloning

snippet
code
CosyVoice (Alibaba, 2024) is an open-source TTS model that supports:

Zero-shot voice cloning โ€” clone from a few seconds of audio

Cross-lingual synthesis โ€” speak a language the reference speaker never spoke

Emotion control โ€” happy, sad, angry, whispering

Fine-grained control โ€” adjust speed, pitch, and style

bash

CosyVoice usage (Python)

from cosyvoice import CosyVoice

snippet
code
model = CosyVoice('CosyVoice-300M-Instruct')

Zero-shot voice cloning

snippet
code
output = model.inference_zero_shot(
text="Welcome to Learn AI Infrastructure",
    prompt_text="reference transcript",
    prompt_speech="reference_audio.wav"

)

Cross-lingual (speak Hindi with English voice)

snippet
code
output = model.inference_cross_lingual(
text="เคจเคฎเคธเฅเคคเฅ‡, เคฎเฅˆเค‚ เคเค• AI เคนเฅ‚เค‚",
    prompt_speech="english_speaker.wav"

)

๐Ÿ“ฆ

Edge TTS: Practical and Free

For practical use, Edge TTS (Microsoft's neural voices via the Edge browser API) offers high-quality synthesis for free:

bash

Install

pip install edge-tts

Basic usage

edge-tts --text "Hello from Learn AI Infrastructure" \

example
code
--voice en-US-GuyNeural \
         --write-media output.mp3

List available voices (400+)

edge-tts --list-voices

Popular voices:

Voice ID Language Style

en-US-GuyNeuralEnglish (US)Male, natural
en-GB-RyanNeuralEnglish (UK)Male, British
hi-IN-MadhurNeuralHindiMale, warm
en-IN-PrabhatNeuralEnglish (Indian)Male, clear

Edge TTS is perfect for content creation, podcast generation, and accessibility โ€” and it's free with no API key required.

๐Ÿš€

The Latency Challenge

Real-time voice conversation requires end-to-end latency under 500ms (ideally under 300ms) for natural feel:

snippet
code
User speaks โ†’ STT (100ms) โ†’ LLM thinking (200-500ms) โ†’ TTS (100ms) โ†’ Audio plays

Total: 400-700ms

GPT-4o approach:

snippet
code
User speaks โ†’ Audio tokens in โ†’ LLM generates audio tokens out โ†’ Decode (50ms)

Total: 250-400ms

The native audio token approach wins because it eliminates two pipeline stages. But it requires the LLM to understand and generate audio directly โ€” a much harder training problem.

๐Ÿ”„

Practical Takeaways

Whisper is the gold standard for STT โ€” open-source, 99 languages, handles noisy audio

Modern TTS uses neural networks end-to-end โ€” from text to phonemes to spectrograms to waveforms

Voice cloning needs just 30 seconds of audio โ€” speaker embeddings capture vocal identity in a vector

GPT-4o generates audio tokens directly โ€” no text-to-speech pipeline, enabling natural conversation

Neural audio codecs (EnCodec) are the foundation โ€” they tokenize audio so LLMs can predict it

Edge TTS is free and production-quality โ€” 400+ neural voices, no API key needed

๐Ÿ—๏ธ

What's Next?

Episode 60: Diffusion Models โ€” How does AI generate images from noise? What are denoising steps, U-Net, and classifier-free guidance? We'll break down how Stable Diffusion and DALL-E turn random static into photorealistic images.

โ† Previous

Ep 58: Multi-modal AI

Next โ†’

Ep 60: Diffusion Models

Next: Episode 60 โ€” Diffusion Models

Take a photo. Add static noise until nothing remains but TV static. Now reverse the process. That's diffusion.

This is part of a 98-episode series covering AI engineering from tokens to production deployment.

โ† Previous Ep 58: Multi-modal AI: How Vision Models Actually See Your Imaโ€ฆ