Level 3 In-Depth AI · Generative AI
Music and Voice Generation
How machines generate speech, voices, music and sound. Classic text-to-speech predicts a spectrogram and turns it into sound with a vocoder. Modern systems compress audio into discrete tokens with a neural codec and generate them with a Transformer, or use diffusion and flow matching. Voice cloning needs only seconds of audio, which makes consent and disclosure essential.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 50 minutes to read, an hour to practise
- Builds on
- 18 concepts →
- Quiz
- 4 questions ↓
This leads to
—The full path from zero — 18 concepts before this one
- What Is AI?
- Probability Basics
- Vectors
- Derivatives and Slopes
- How Machines Learn
- Probability Distributions
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- Supervised Learning
- Audio as Data
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- What Generative Models Do
- Music and Voice Generation
Read them roughly in this order. See it on the concept map →
Why it matters
Generated speech is everywhere: the voices of assistants and phone menus, audiobooks and video narration, screen readers, dubbing into other languages, and the spoken "voice mode" of chat assistants that answer in under a second. Since 2023, systems have been able to clone a voice from a few seconds of audio. Since 2024, services such as Suno and Udio, and open models such as MusicGen and Stable Audio, generate full songs or instrumental music from a text description. Video generators now add synchronised dialogue and sound effects (Video Generation).
Audio is a hard target for generative models. It is extremely long: CD-quality sound has 44,100 numbers per second per channel, so a three-minute song is about 16 million numbers. And people are very sensitive to tiny errors: a click, a metallic buzz, a wrong stress on a syllable. The history of audio generation is the history of finding compact representations that keep what the ear cares about. The modern answer, audio tokens from a neural codec, connects audio directly to the language-model machinery of GPT and Decoder-Only Models.
The intuition
Imagine writing down a piece of music for someone else to play. You wouldn't record the air pressure 44,100 times a second. You would write a score: which notes, when, how loud, on which instrument. A good performer turns the score back into sound. The score is thousands of times shorter than the recording and keeps nearly everything that matters.
Audio generators work the same way, in two stages:
- A compact "score". A model is trained to turn audio into a much shorter representation and back again. There are two common kinds:
- a mel spectrogram, a picture of which pitches are loud at each moment (Audio as Data), turned back into sound by a neural vocoder;
- audio tokens: a neural audio codec compresses each few milliseconds of sound into a handful of integers from fixed codebooks, like words from a vocabulary, and decodes them back to sound.
- A composer for the score. A generative model produces the compact representation from the input (text, a voice sample, a melody). For tokens, this is usually a Transformer predicting the next token, exactly like an LLM predicting the next word. For spectrograms and continuous latents, it is often diffusion or Normalizing Flows and Flow Matching.
Key idea Modern audio generation = compress sound into a short sequence (spectrogram frames or codec tokens) + generate that sequence with a Transformer, diffusion or flow model + decode it back to a waveform. Codec tokens let speech and music be generated with the same next-token machinery as text.
How it works
Generating raw samples: WaveNet
The first neural system to sound truly natural was WaveNet (DeepMind, 2016). It is an autoregressive model that predicts each audio sample from the thousands before it, using stacks of dilated convolutions to see far back cheaply. Its speech was a big jump in naturalness. But generating 16,000–24,000 samples per second one at a time was far too slow for real use, until distillation into a parallel model in 2017. The lesson: operate at a coarser time scale.
Classic text-to-speech: spectrogram plus vocoder
The standard text-to-speech (TTS) pipeline from about 2017 to 2022 had two networks:
- An acoustic model (for example Tacotron 2, 2017, or the faster, non-autoregressive FastSpeech 2) reads characters or phonemes and outputs a mel spectrogram. That is typically 80 frequency bands every 10–12 milliseconds, about 80–100 frames per second instead of 22,050 samples.
- A vocoder turns the spectrogram into a waveform. A spectrogram keeps the loudness of each frequency band but discards phase, so the vocoder has to invent a waveform consistent with it. GAN vocoders such as HiFi-GAN (2020) do this in a single fast pass, using the adversarial training from Generative Adversarial Networks to avoid the metallic buzz of older methods.
This pipeline gives clear, controllable speech and is still widely used on phones and embedded devices. Its limits are that voices come from the training speakers, and that natural variation (emotion, laughter, hesitations) is hard to produce.
Neural audio codecs and residual vector quantisation
A neural audio codec (SoundStream, 2021; EnCodec, 2022; DAC, 2023) is an autoencoder with a discrete bottleneck:
- A convolutional encoder turns the waveform into a sequence of vectors, for example 75 per second for EnCodec at 24 kHz, each summarising about 13 milliseconds.
- Residual vector quantisation (RVQ) replaces each vector by entries from a stack of learned codebooks, typically each with 1,024 entries. The first codebook picks the nearest entry. The second codebook quantises what the first missed (the residual). The third quantises what is still left, and so on. Each codebook adds detail, so the first carries the coarse content and later ones refine it.
- A decoder turns the summed codebook vectors back into a waveform. Training combines reconstruction losses with an adversarial loss, so the result sounds natural rather than just matching numerically.
Each frame becomes a short column of integers, the audio tokens. The bitrate is easy to compute. With codebooks of 1,024 entries ( bits each) at 75 frames per second:
So gives 1.5 kbps and gives 6 kbps, EnCodec's standard settings. Uncompressed 16-bit audio at 24 kHz is 384 kbps, so 6 kbps is 64 times smaller. One codec can serve several bitrates: use more codebooks for higher quality.
Generating tokens with a Transformer
Once audio is tokens, generation is language modelling (Language Modeling and Next-Token Prediction):
- AudioLM (Google, 2022) continued speech and piano recordings by predicting first "semantic" tokens (capturing content) and then codec tokens (capturing sound).
- VALL-E (Microsoft, 2023) framed TTS as predicting codec tokens from phonemes plus a 3-second recording of the target speaker. It was trained on 60,000 hours of English speech. With no fine-tuning, it continued in the prompt speaker's voice, including their recording conditions. This is zero-shot TTS, also called voice cloning.
- MusicGen (Meta, 2023) generates music from a text description, or a text plus a melody, using a single Transformer over EnCodec tokens (32 kHz, 4 codebooks at 50 frames per second). It was trained on about 20,000 hours of licensed music. A "delay" pattern offsets each codebook by one step, so one Transformer can predict all four streams in parallel.
Token counts stay manageable. Thirty seconds of MusicGen audio is frames, or 6,000 tokens across 4 codebooks. That is a long but ordinary sequence for a Transformer, where the raw waveform would be 960,000 samples.
Diffusion and flow matching for audio
The other main approach generates continuous representations:
- Stable Audio (2023) is Latent Diffusion and Stable Diffusion for sound. A VAE compresses audio, a diffusion model generates latents from a text prompt, and extra inputs for start time and duration let it produce clips of a requested length.
- Voicebox (Meta, 2023) and later TTS systems such as F5-TTS use Normalizing Flows and Flow Matching to generate speech features, filling in masked parts of a recording. This supports TTS, editing a word in a sentence, and noise removal with one model.
Many current systems are hybrids: a Transformer produces coarse tokens or semantic content, and a diffusion or flow model renders fine acoustic detail.
Speech-to-speech and voice assistants
The newest voice assistants skip the text step. Speech-native models such as OpenAI's GPT-4o (2024) and Kyutai's open Moshi (2024) take audio tokens in and produce audio tokens out within one multimodal model (Multimodal LLMs). This keeps tone and emotion and allows replies within a few hundred milliseconds. Older assistants chained speech recognition (Speech Recognition), an LLM and a TTS system, which added delay and lost how things were said.
Measuring quality
- MOS (mean opinion score): listeners rate naturalness from 1 to 5. Human judgement is still the gold standard.
- Intelligibility: transcribe the generated speech with a recogniser and compute the word error rate.
- Speaker similarity: cosine similarity between speaker embeddings of the reference and the generated voice (Dot Product, Norms and Similarity).
- FAD (Fréchet Audio Distance) for music and sound: the audio version of FID for images.
In code
You can build the core of a codec, residual vector quantisation, in a few lines of NumPy and scikit-learn. Real codecs learn a neural encoder and decoder too. Here the "encoder" just chops the waveform into 2-millisecond frames, and the codebooks are learned with k-Means Clustering on 8 seconds of a synthetic melody, then tested on the last 2 seconds:
import numpy as np
from sklearn.cluster import KMeans
# Ten seconds of a synthetic melody at 16 kHz: random notes of 0.25 s, each a tone plus an overtone
rng, sr = np.random.default_rng(0), 16_000
scale = [262, 294, 330, 349, 392, 440, 494, 523] # C major, in hertz
f = np.repeat(rng.choice(scale, size=40), sr // 4) # 40 notes x 0.25 s
t = np.arange(len(f)) / sr
audio = 0.6 * np.sin(2 * np.pi * f * t) + 0.2 * np.sin(2 * np.pi * 2 * f * t) + 0.01 * rng.normal(size=len(t))
frames = audio.reshape(-1, 32) # 2 ms frames: 500 frames per second
train, test = frames[:4000], frames[4000:] # learn codebooks on 8 s, test on the last 2 s
res_tr, res_te, recon = train.copy(), test.copy(), np.zeros_like(test)
for stage in range(4): # residual vector quantisation
km = KMeans(n_clusters=256, n_init=1, random_state=stage).fit(res_tr) # a 256-entry codebook
res_tr -= km.cluster_centers_[km.labels_]
codes = km.predict(res_te) # one 8-bit token per frame per stage
recon += km.cluster_centers_[codes]
res_te -= km.cluster_centers_[codes] # the next codebook encodes what is left
snr = 10 * np.log10((test ** 2).sum() / ((test - recon) ** 2).sum())
print(f"{stage + 1} codebook(s): {(stage + 1) * 8 * 500 / 1000:4.0f} kbps, test signal-to-noise {snr:5.1f} dB, "
f"first tokens {codes[:4]}")
print("raw 16-bit audio:", 16 * sr / 1000, "kbps")
# 1 codebook(s): 4 kbps, test signal-to-noise 23.7 dB, first tokens [139 215 22 222]
# 2 codebook(s): 8 kbps, test signal-to-noise 30.2 dB, first tokens [199 185 89 65]
# 3 codebook(s): 12 kbps, test signal-to-noise 31.9 dB, first tokens [ 45 180 174 202]
# 4 codebook(s): 16 kbps, test signal-to-noise 33.0 dB, first tokens [228 177 90 66]
# raw 16-bit audio: 256.0 kbps
Signal-to-noise ratio (SNR) compares the signal's energy with the error's on a logarithmic scale. Every 10 dB means 10 times less error energy. The first codebook does most of the work, and each later one adds less. A transformer trained on such token columns could now "compose" new melodies. Real codecs reach far better quality at lower bitrates because their neural encoders learn which details the ear ignores.
With pretrained models, the Hugging Face transformers library offers one-line pipelines. These download models, so they are not run here; written against the 2025 API:
import soundfile as sf
from transformers import pipeline
tts = pipeline("text-to-speech", model="facebook/mms-tts-eng") # a small VITS voice
speech = tts("Generative models can now speak, sing and compose.")
sf.write("speech.wav", speech["audio"].squeeze(), speech["sampling_rate"])
music = pipeline("text-to-audio", model="facebook/musicgen-small") # EnCodec tokens + Transformer
clip = music("calm lo-fi beat with soft piano and rain", forward_params={"do_sample": True, "max_new_tokens": 256})
sf.write("music.wav", clip["audio"].squeeze(), clip["sampling_rate"]) # 256 frames at 50 Hz ≈ 5 s
Common pitfalls
- Judging with numbers alone. A codec or TTS model can score well on signal-to-noise or word error rate and still sound robotic. Listen, and run blind listening tests when the decision matters.
- Sample-rate mismatches. Feeding 44.1 kHz audio to a model trained at 24 kHz, or saving output with the wrong rate, changes pitch and speed or ruins quality. Resample explicitly.
- Long-form drift. Token models can lose the voice, repeat or speed up over long passages. Generate sentence by sentence or paragraph by paragraph, conditioning each piece on the last.
- Pronunciation of names, numbers and jargon. Normalise text first ("Dr." → "Doctor", "2025" → "twenty twenty-five") and use phoneme input or pronunciation dictionaries where available.
- Assuming music models are free to use commercially. Check licences. Some open music models are released for non-commercial use only.
Watch out A few seconds of someone's voice is now enough to imitate them convincingly. Cloned voices have been used in phone scams ("Mum, I'm in trouble") and in political robocalls. In 2024 the US FCC ruled that AI-generated voices in robocalls fall under existing robocall restrictions. Only clone a voice with the speaker's explicit, informed consent, disclose synthetic speech to listeners, and prefer providers that watermark output and verify consent. Agree on a family code word for emergency calls. Music generation raises its own copyright questions: major record labels sued two leading music-generation companies, Suno and Udio, in 2024. From late 2025 some labels settled and signed licensing deals with them (Universal and Warner with Udio, Warner with Suno), while other claims were still in court as of 2026. See Deepfakes and Misinformation and Privacy, Data and Copyright.
Where it leads
- Speech Recognition: the reverse task, audio to text, which also supplies transcripts to train TTS.
- Multimodal LLMs: speech-native assistants that listen and speak in one model.
- Video Generation: joint generation of picture and sound.
- Language Modeling and Next-Token Prediction and Tokenization: the ideas that audio tokens reuse.
- Latent Diffusion and Stable Diffusion and Normalizing Flows and Flow Matching: the continuous alternatives for music and speech.
A bit of history
Speech synthesis is old. Bell Labs' Voder spoke at the 1939 World's Fair. From the 1980s to the 2010s, systems glued together recorded snippets (concatenative synthesis) or used statistical models (parametric synthesis), which sounded robotic. WaveNet (2016) changed expectations overnight, and Tacotron 2 (2017) showed natural speech straight from text. Fast non-autoregressive models and GAN vocoders (HiFi-GAN, 2020) made it practical, and end-to-end models such as VITS (2021) merged the two stages.
The codec era began with SoundStream (Google, 2021) and EnCodec (Meta, 2022). It led to AudioLM (2022), VALL-E (January 2023), MusicGen (June 2023) and a wave of zero-shot voice-cloning services. Meanwhile Jukebox (OpenAI, 2020) had shown raw-audio song generation with VQ-VAE tokens, slowly. Stable Audio (2023) brought latent diffusion to music. Suno and Udio (2024) made full songs with vocals from a prompt available to everyone. Speech-native assistants (GPT-4o, Moshi, 2024) and joint audio-video generation (Veo 3, 2025) followed. As with images and video, the techniques now change every few months. Treat specific products as a snapshot.
Try it
- In the code, change the codebook size from 256 to 16 (4 bits per token) and run with 8 stages. How do bitrate and signal-to-noise compare with 256 entries and 4 stages?
- Compute how many EnCodec tokens (24 kHz, 75 frames per second, 8 codebooks) a one-hour podcast would take, and compare with the number of text tokens in its transcript (assume 150 words per minute and about 1.3 tokens per word).
- Write a short consent statement you would require before cloning a colleague's voice for a training video. What would it allow, for how long, and how could they withdraw?
Hint for 2: tokens of audio versus about tokens of text.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Hugging Face Audio Course
A free hands-on course on audio with Transformers, from waveforms and spectrograms to audio classification, speech recognition with Whisper and text-to-speech.
SoundStream: An End-to-End Neural Audio Codec
A neural codec with residual vector quantisation that turns audio into discrete tokens.
High Fidelity Neural Audio Compression (EnCodec)
Meta's neural audio codec, used as the tokenizer of MusicGen and many speech models.
Neural Codec Language Models are Zero-Shot Text to Speech Synthesizers (VALL-E)
Text-to-speech as language modelling over codec tokens; clones a voice from a 3-second prompt.
Simple and Controllable Music Generation (MusicGen)
A single Transformer over EnCodec tokens that generates music from text or a melody.
WaveNet: A Generative Model for Raw Audio
An autoregressive network over raw audio samples that produced far more natural speech than previous systems.
Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions (Tacotron 2)
The classic two-stage text-to-speech recipe: text to mel spectrogram, then a neural vocoder to waveform.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/audio-generation.md