Audio models can say a sentence in a chosen voice, or write a short piece of music from a text prompt. Sound is a very long list of numbers, so the first step is to shrink it into short, simple pieces. This lesson shows how, and it dates every product statement because prices, limits and legal status change fast.
After this lesson, you will be able to:
Understand neural audio codecs (SoundStream, EnCodec) — how raw waveforms get compressed to 50-75 discrete tokens per second so transformers can model them
Trace the TTS evolution from Tacotron's autoregressive mel-spectrogram era to VALL-E's in-context voice cloning from a 3-second sample to today's commercial real-time voice products
Compare music generation systems (MusicLM, MusicGen, Stable Audio, Suno, Udio) — what each architecture is, what audio quality and prompt-following look like in 2026
Apply latent audio diffusion vs autoregressive token modeling — when each wins, and how watermarking (AudioSeal) is used as a partial hedge against deepfake misuse
Audio follows the same recipe as images. Turn the sound into tokens, train a model on the tokens, make new tokens, then turn them back into sound. Audio only needs a different compressor, called a codec.
Words you need8 terms
Sound written as a long list of numbers, one for each tiny slice of time.
How many of those numbers are stored per second. 24 kHz means 24,000 per second.
A picture of sound. Time runs across, pitch runs up, and brightness shows how loud each pitch is.
A compressor for sound. The encoder shrinks audio to a few integers, and the decoder turns them back into audio.
One integer from the codec. A model reads and writes sequences of tokens, as a chat model does with words.
A fixed list of vectors. The codec replaces each piece of sound with the number of its nearest entry.
Using several codebooks in a row. Each one encodes what the earlier ones missed.
How many bits per second the compressed audio needs. A lower bitrate is smaller but sounds worse.
Audio at 24 kHz is 24,000 floating-point samples per second. A 30-second clip is 720,000 samples. Modeling that directly with a transformer is hopeless — attention is O(N²) in sequence length, and 720K tokens is two orders of magnitude beyond what's feasible. The entire field of modern audio AI rests on solving this with neural audio codecs: learned tokenizers that compress audio to 50-75 discrete tokens per second while preserving perceptual quality.
The same path as a picture. The model learns from the tokens of real recordings, then predicts new tokens.
The codec numbers in this lesson (24,000 samples per second, 75 frames per second) are not arbitrary. Two small results explain them: how fast you must sample to keep a frequency, and how many frames a clip yields.
Try a short and a long window on a one second clip with two tones 20 Hz apart and a click, and watch which one each window can locate.
Loading visualization...
Do: Slide the window up to 4096 samples, then down to 128. Watch the two close tones and the click.
Notice: Long window: the two tones split apart and the click smears. Short window: the click is sharp and the tones merge.
Why: A long window sees more of each wave, so pitch is clear. A short window sees less time, so timing is clear.
Modern audio generative AI starts with a neural codec. The codec has three jobs: encode waveform → compressed tokens, decode tokens → waveform, and minimize perceptual distortion.
Residual Vector Quantization (RVQ) is the key trick. Single-codebook VQ-VAE caps quality (one codebook of size 1024 = only 10 bits per frame). RVQ stacks multiple codebooks: codebook 1 quantizes the encoder output, codebook 2 quantizes the residual error from codebook 1, codebook 3 quantizes the residual from codebooks 1+2, and so on. Each additional codebook adds another 10 bits of fidelity.
One snap to a codebook is easy to see in two dimensions. Try it before reading the formula.
Loading visualization...
Do: Drag the dot to sit midway between two codes, then right on top of one.
Notice: The dot snaps to the nearest code. Midway leaves a big gap; on top leaves almost none.
Why: That leftover gap is what the next codebook encodes, so more codebooks give finer sound.
Drawn stand-in: 8 fixed codes, not a trained codec.
The two formulas above say the same thing in two forms: a sum of chosen codebook vectors, and a loop that quantises what is left over. The next derivations show why they agree, and how bits and bitrate follow.
Why this is a generative-AI building block, not just a compression scheme: EnCodec produces a discrete token sequence at 75 tokens/sec * K codebooks. A transformer trained on these tokens (VALL-E, MusicGen) generates new audio in the same way GPT generates text. The decoder turns generated tokens back into waveform.
The architectural shift in TTS is from two-stage cascade (text → mel-spectrogram → waveform) to end-to-end token modeling (text → audio tokens directly).
Tacotron 2 (2017). Encoder reads text, attention mechanism aligns text to spectrogram frames, decoder generates mel-spectrogram autoregressively. A separate WaveNet vocoder converts mel to waveform. Slow but high-quality. Per-voice training — need hours of audio per speaker.
FastSpeech 2 (2021). Replace autoregressive generation with parallel non-autoregressive prediction + duration model. Much faster inference than Tacotron 2.
VITS (2021). End-to-end variational TTS combining flow + variational autoencoder + adversarial loss. First to skip mel-spectrogram intermediate.
VALL-E (2023). The breakthrough: treat TTS as a conditional language model on EnCodec tokens. Train on 60,000 hours of audio with the objective "given text + a 3-second voice prompt in EnCodec tokens, predict the rest of the audio tokens". Result, according to the paper's demos: clone a speaker from a 3-second sample with no fine-tuning. The weights were never released.
Product details as of Oct 2026; check current status.
System
Approach
Voice cloning
License / access
ElevenLabs
Not published
From a short sample (length depends on the plan)
API only
OpenAI TTS
Not published
Preset voices
API only
VALL-E X / Microsoft
Multilingual codec language model
3-second prompt in the paper
Weights not released
Coqui XTTS v2
GPT-style model over audio codes, plus a speaker embedding
About 6-second reference clip
Open weights, non-commercial Coqui licence
OpenVoice (MyShell)
Tone color converter
Short reference clip
Open weights (check the licence)
Sesame CSM-1B
Conversational speech model
Voice set by audio context
Open weights (check the licence)
GPT-4o voice mode
End-to-end multimodal
Preset voices
OpenAI API
The trade-off: closed APIs are easy to use and often lead on quality, while open weights give control and lower cost. How big the gap is changes quickly, so listen to both on your own text.
Music is harder than speech. Speech is a roughly-stationary signal with constrained phonetic structure. Music has long-range structure (verses, choruses, motifs), polyphonic harmony, instrument timbres, and rhythmic precision — all simultaneously.
The product in this formula is not a modelling assumption: it is an exact identity that holds for any distribution over the tokens.
MusicGen treats music as language: text-conditioned next-token prediction over EnCodec tokens. Open code, three sizes (300M / 1.5B / 3.3B params), fast enough for interactive iteration. The released weights are CC-BY-NC (non-commercial); Meta says it trained on licensed music.
Latent diffusion in audio domain. Encode audio to a latent space via a VAE, then run a diffusion U-Net conditioned on text embeddings. Same architecture as Stable Diffusion image but in 1D audio latent space. Produces 90+ second clips with strong long-range coherence.
Closed-weight systems generating full songs (vocals + instrumentation + lyrics + structure) from text prompts. Architecture details are unpublished. Record labels, through the RIAA, sued both companies in June 2024, alleging they trained on copyrighted recordings without a licence. Reports in late 2025 described settlements and licensing deals for some of these cases. As of Oct 2026, check the current status.
What Do You Think?
You have 30 minutes of clean recordings of one speaker, with the speaker's written consent. Which approach is the most reasonable starting point with open tools?
Adapting a pretrained multi-speaker model is a sound default here. Per-voice training from scratch (option 1) needs far more than 30 minutes. VALL-E showed that a short prompt can steer a codec language model, but its weights were never released, and the paper does not claim that a 3-second prompt gives the best quality. How well any cloner works depends on how clean the reference audio is and on the model.
AudioGen (Meta, 2022) — Sound effects and Foley generation.
When to use which: Autoregressive (VALL-E, MusicGen) wins on streaming and short clips because tokens come out one frame at a time. Diffusion (Stable Audio) wins on long-form coherence because the entire output is denoised together. Latency: AR is faster to first sound, diffusion is faster to total output for long clips.
This lesson has two cells. The first needs a GPU and downloads model weights, so it is a read-only copy for Google Colab. The second runs here in your browser with numpy: a toy residual quantizer that shows why each extra codebook helps.
PythonRead-only reference
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Copy to Colab (needs transformers, torch and model downloads; it cannot run in the browser)
# Generate a 5-second music clip with MusicGen, then a voice clone with XTTS
# (Note: requires audiocraft and TTS packages installed)
# === Music generation with MusicGen ===
from transformers import MusicgenForConditionalGeneration, AutoProcessor
import scipy.io.wavfile
print("Loading MusicGen-small (300M params)...")
model = MusicgenForConditionalGeneration.from_pretrained('facebook/musicgen-small')
processor = AutoProcessor.from_pretrained('facebook/musicgen-small')
# Generate from text prompt
prompts = [
'80s synthwave with driving bass and analog drums',
]
inputs = processor(text=prompts, padding=True, return_tensors='pt')
# 256 tokens at 50 Hz = 5.12 seconds
audio_values = model.generate(**inputs, max_new_tokens=256)
sampling_rate = model.config.audio_encoder.sampling_rate
scipy.io.wavfile.write(
'synthwave.wav',
rate=sampling_rate,
data=audio_values[0, 0].numpy()
)
print(f"Wrote synthwave.wav at {sampling_rate} Hz")
# === Voice cloning with Coqui XTTS v2 ===
# from TTS.api import TTS
# tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2")
# tts.tts_to_file(
# text="The acoustic models we trained yesterday now sound human.",
# speaker_wav="reference_voice.wav", # 6-30 sec sample of target voice
# language="en",
# file_path="cloned_output.wav"
# )
print("CHALLENGE: extend to 30 seconds (max_new_tokens=1500)")
print("CHALLENGE: try genre fusion: 'jazz fusion meets dubstep'")
print("CHALLENGE: condition on a melody (audio-conditioned generation)")
Now the browser version. It cuts a synthetic voice-like wave into 320-sample frames (75 per second, like EnCodec), learns a codebook for each stage with k-means, and measures how the error falls as stages are added.
pythonplayground.py · Pyodide
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Tests: Run the script. It should print 300 frames at 75 per second, then four lines in which the SNR rises with each codebook (about 10, 15, 17 and 19 dB) while the bitrate grows by 375 bits/s per stage, and finally 'All checks passed'. This is a drawn stand-in for a neural codec: k-means on raw frames, not a trained encoder.
Audio generative AI has a deepfake problem — voice cloning is trivially abusable for fraud, harassment, and political disinformation. The technical mitigation is watermarking: embed an imperceptible signal into generated audio that can be detected by a verifier.
AudioSeal (Meta, 2024) is an open-source watermark for generated speech. It adds a signal that people do not hear, and a detector can flag it in short excerpts. Its paper reports robustness to some edits, such as compression and added noise, and weaker results against others, such as strong pitch shifts. It is a partial defence, not a guarantee.
Stable Signature (Meta) is a similar idea for images made by latent diffusion models.
Limitations: watermarks can be stripped by sophisticated adversaries (denoising, re-vocoding, or generation through a non-watermarked pipeline). The C2PA standard adds cryptographically-signed provenance metadata as a complement, not a replacement. On regulation: the EU AI Act (Article 50) requires providers of systems that generate synthetic audio to mark outputs in a machine-readable way, with the duty applying from August 2026; it names no specific tool, and the timeline may change, so check it. The US Executive Order 14110, which asked for watermarking standards, was revoked in January 2025.
Neural audio codecs (SoundStream, EnCodec) make audio look like text to a transformer. By tokenizing 24 kHz waveforms to 75 discrete tokens/sec, they enable language-model-style training on audio with the same infrastructure that powers GPT
VALL-E and successors made voice cloning a short-prompt problem (the VALL-E paper used 3-second prompts). The same in-context-learning paradigm that makes GPT few-shot also lets neural codec language models clone speakers without fine-tuning
Commercial music generators such as Suno and Udio reached products people use, triggering copyright lawsuits and forcing the industry to confront training-data provenance
Latency matters a great deal for voice. OpenAI reported about 320 ms on average for GPT-4o voice mode, which handles audio in one model instead of chaining three
Watermarking and provenance are becoming legal expectations. EU AI Act Article 50 requires machine-readable marking of synthetic audio from August 2026 without naming a tool; US Executive Order 14110 was revoked in January 2025
An architecture diagram: boxes are components, arrows show the direction data flows, and moving dots mark the live flow.
Architecture diagram "From sound to tokens and back" with 8 components (Waveform, Codec encoder, Codec tokens, Text prompt, Model, New tokens, Codec decoder, New waveform) joined by 7 arrows showing how data flows between them.