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

Music & Audio Generation: Codecs, Tokens and Diffusion

Why raw audio is hard to generate, how neural audio codecs (SoundStream, EnCodec) turn sound into tokens, and how AudioLM, MusicGen, AudioLDM and Jukebox generate speech, music and sound effects.

Advanced~26 min·6 references
Key terms
Neural audio codecGenerative modelTokenDiffusion modelLatent diffusionClassifier-free guidance (CFG)

A three-minute song at 44.1 kHz stereo is about 16 million numbers, and it must stay coherent over that whole span: the chorus should come back, the tempo should not drift, the chords should resolve. Text models handle a few thousand tokens; image models a few thousand latent patches. The breakthrough for audio generative models was to first compress sound into a short sequence of discrete tokens with a neural Neural audio codec, and then reuse the two strongest generative recipes we know: Transformer language models and Latent diffusion.

≈
Analogy: LEGO bricks for sound
Instead of sculpting a statue grain by grain of sand (raw samples), you first build a catalogue of LEGO bricks that can rebuild almost any sound (the codec's codebooks). Then a composer only has to choose which brick goes next — a much shorter and easier sequence. Coarse bricks lay out the shape; finer bricks add detail on top.

1. Neural audio codecs: SoundStream and EnCodec

SoundStream (Zeghidour et al., 2021)[1] and EnCodec (Défossez et al., 2022)[2] are convolutional autoencoders: an encoder downsamples the waveform into latent frames (e.g. 75 frames per second for 24 kHz EnCodec), a residual vector quantizer (RVQ) turns each frame into a few integers, and a decoder reconstructs the waveform. They are trained with reconstruction losses (waveform and multi-scale mel) plus adversarial discriminators, so the result sounds good rather than merely matching on average. With quantizer dropout, one model supports several bitrates. At 6 kbps EnCodec beats classic codecs like Opus at much higher bitrates in listening tests.

  1. Quantizer 1 picks the nearest of K codebook vectors (e.g. K = 1024) to the latent frame z → token q₁.
  2. Compute the residual r₁ = z − c(q₁). Quantizer 2 quantizes r₁ → token q₂, and so on for N_q stages.
  3. The frame is reconstructed as the sum c(q₁) + c(q₂) + … The first codebooks carry coarse content (pitch, phonemes, rhythm); later ones add fine detail (timbre, noise, crispness).
bitrate = frame_rate × N_q × log₂(K) EnCodec 24 kHz: 75 × N_q × 10 bit → 1.5 kbps (N_q=2) … 24 kbps (N_q=32)
Compare with 384 kbps for uncompressed 24 kHz / 16-bit mono audio.
In words: A neural codec sends, for every latent frame, one index per codebook; an index into a codebook of K entries costs log₂(K) bits. Multiply by the number of codebooks and frames per second to get bits per second. Dropping codebooks lowers the bitrate (and quality) without retraining.
Symbols(hover a symbol in the formula)
bitrate
bits per second needed to transmit the tokens
frame_rate
latent frames per second (75 for EnCodec 24 kHz, 50 for MusicGen's 32 kHz codec)
N_q
number of RVQ codebooks (quantizers) used
log₂(K)
bits per token: log base 2 of the codebook size
K
entries per codebook (1024 in EnCodec 24 kHz → 10 bits)
kbps
kilobits per second (1 kbps = 1000 bit/s)
▸Worked example
EnCodec 24 kHz, K = 1024 → log₂(1024) = 10 bits: N_q = 2: 75 × 2 × 10 = 1,500 bit/s = 1.5 kbps N_q = 8: 75 × 8 × 10 = 6,000 bit/s = 6 kbps N_q = 32: 75 × 32 × 10 = 24,000 bit/s = 24 kbps MusicGen codec: 50 × 4 × log₂(2048) = 50 × 4 × 11 = 2,200 bit/s = 2.2 kbps Raw 24 kHz 16-bit mono: 24,000 × 16 = 384,000 bit/s → 6 kbps is 64× smaller.

2. Language models over audio tokens

AudioLM (Borsos et al., 2022)[3] showed that a Transformer can continue speech or piano music convincingly by predicting two kinds of tokens: *semantic* tokens (k-means clusters of a self-supervised speech model, capturing content and long-term structure at a low rate) and *acoustic* tokens (SoundStream codes, capturing voice and recording quality). Generation is hierarchical: semantic tokens first, then coarse acoustic tokens conditioned on them, then fine acoustic tokens. Given a 3-second prompt, it continues speech in the same voice with plausible (though meaningless) words.

MusicGen (Copet et al., 2023)[4] simplified this into a single-stage Transformer decoder over EnCodec tokens (32 kHz, 4 codebooks at 50 Hz). Instead of predicting the 4 codebooks one after another (4× longer sequence) or all at once (ignores their dependency), it uses a delay pattern: codebook k is shifted by k steps, so at each step the model predicts all 4 streams in parallel while finer codebooks still see the coarser ones from earlier steps. Text descriptions are encoded with a frozen T5 encoder and injected through cross-attention; an optional melody can be given as a chromagram. It was trained on about 20,000 hours of licensed music and uses Classifier-free guidance (CFG) at sampling time.

Loading interactive…
Codec + language model in one picture. Walk through it: audio is squeezed into a few streams of integers by residual vector quantization (top), a text-conditioned Transformer learns to continue those streams (bottom), and the codec decoder turns tokens back into sound. Tap the − circles to see how each quantizer only encodes what the previous ones missed.

3. Diffusion for audio: AudioLDM

AudioLDM (Liu et al., 2023)[5] borrows the Stable Diffusion recipe: a VAE compresses mel spectrograms into a small latent image, a Diffusion model denoises that latent, and a HiFi-GAN vocoder turns the decoded mel back into audio. Conditioning comes from CLAP, a contrastive audio–text model (like CLIP for sound). The trick: CLAP puts audio and text in the same embedding space, so training can condition on the *audio's own* CLAP embedding (no captions needed), while at inference you condition on the *text* embedding. It excels at sound effects and ambiences (“rain on a tin roof with distant thunder”).

4. Jukebox: raw audio with lyrics

Jukebox (Dhariwal et al., 2020)[6] was the first model to generate minutes of raw 44.1 kHz music with singing. A hierarchical VQ-VAE compresses audio at three levels (8×, 32× and 128× fewer steps); a large sparse Transformer prior generates the top level conditioned on artist, genre and lyrics, and upsampler priors fill in the lower levels. The results were striking but noisy, and rendering one minute took hours on a GPU — showing why later work moved to compact codecs and faster samplers.

ModelRepresentationGeneratorBest at
Jukebox (2020)3-level VQ-VAE codes, 44.1 kHzSparse Transformer priorsSongs with lyrics (slow)
AudioLM (2022)Semantic + SoundStream tokens3-stage Transformer LMSpeech / piano continuation
MusicGen (2023)EnCodec 32 kHz, 4 codebooksSingle Transformer, delay patternText/melody → instrumental music
AudioLDM (2023)VAE latent of mel spectrogramLatent diffusion + CLAPSound effects, ambience, text-to-audio

The knobs

knobguidance_scale
What it is
Classifier-free guidance strength: how strongly sampling is pushed toward the text condition versus the unconditional model.
↑ If you increase it
Output follows the prompt more literally (the right instruments and mood), but diversity drops and, at high values, audio becomes harsh or distorted.
↓ If you decrease it
More varied, sometimes more natural audio that may ignore parts of the prompt.
Typical values
≈ 3 for MusicGen; 2.5–4 for AudioLDM.
knobtemperature / top_k (token models)
What it is
Sampling settings for codec-token language models like MusicGen: temperature reshapes the next-token distribution, top-k keeps only the k most likely tokens.
↑ If you increase it
More surprising, varied music; too high produces noise bursts, glitches and loss of rhythm.
↓ If you decrease it
Safer, repetitive output; greedy decoding often loops the same bar or collapses into silence.
Typical values
temperature 1.0 with top_k = 250 (MusicGen default).
knobduration / max_new_tokens
What it is
Length of the generated clip. For MusicGen, tokens are produced at 50 per second, so 256 tokens ≈ 5 s.
↑ If you increase it
Longer pieces, but cost grows (attention is quadratic in length) and long-range structure tends to wander; beyond the training length (~30 s) quality drops unless you use windowed continuation.
↓ If you decrease it
Fast previews, ideal for iterating on prompts; too short to develop a musical phrase.
Typical values
5–30 s per generation.
knobcodec bandwidth (number of codebooks N_q)
What it is
How many RVQ codebooks are used per frame, i.e. the codec bitrate.
↑ If you increase it
Higher fidelity reconstruction (cleaner cymbals, less “underwater” sound), but more tokens for a generative model to predict.
↓ If you decrease it
Tiny bitrates suitable for streaming and easier generation, but artifacts and muffled timbre.
Typical values
EnCodec 24 kHz: 1.5, 3, 6, 12 or 24 kbps; MusicGen uses 4 codebooks.

In code

python
import scipy.io.wavfile
from transformers import AutoProcessor, MusicgenForConditionalGeneration

processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")

inputs = processor(text=["gamelan-inspired ambient track with soft bamboo flute",
                         "upbeat dangdut rhythm with bass and kendang"],
                   padding=True, return_tensors="pt")

audio = model.generate(**inputs, do_sample=True, guidance_scale=3.0,
                       max_new_tokens=256)          # ~5 seconds at 50 tokens/s
sr = model.config.audio_encoder.sampling_rate       # 32000
scipy.io.wavfile.write("musicgen_0.wav", rate=sr, data=audio[0, 0].numpy())
Text-to-music with MusicGen in Hugging Face Transformers. The model's output reflects its (mostly Western) training data — niche genres may sound off.
python
import librosa
from transformers import EncodecModel, AutoProcessor

model = EncodecModel.from_pretrained("facebook/encodec_24khz")
processor = AutoProcessor.from_pretrained("facebook/encodec_24khz")

wav, _ = librosa.load("speech.wav", sr=processor.sampling_rate)   # 24 kHz mono
inputs = processor(raw_audio=wav, sampling_rate=processor.sampling_rate,
                   return_tensors="pt")

enc = model.encode(inputs["input_values"], inputs["padding_mask"], bandwidth=6.0)
print(enc.audio_codes.shape)   # last two dims: N_q=8 codebooks x frames (75 per second)
recon = model.decode(enc.audio_codes, enc.audio_scales, inputs["padding_mask"])[0]
Encode audio into discrete EnCodec tokens and decode it back. Try bandwidth=1.5 vs 24.0 and listen to the difference.
!
Pitfalls, evaluation and rights
Evaluation is hard: the common automatic metric is Fréchet Audio Distance (FAD), comparing embedding statistics of generated vs real audio, plus CLAP score for text adherence — but human listening tests remain essential. Memorization: large models can regurgitate training melodies; check for near-duplicates before commercial use. Copyright and consent: training on unlicensed recordings, or imitating a specific artist's voice, raises legal and ethical issues; prefer models trained on licensed data and respect platform rules on AI-generated music. Disclosure: label AI-generated tracks, especially when they imitate real performers.
▸Go deeper: why the delay pattern works

With 4 codebooks and T frames, the exact autoregressive factorisation would need 4T sequential steps. Predicting all 4 codebooks of frame t independently needs only T steps but ignores that codebook 2 refines codebook 1. In the delay pattern, at step s the model predicts codebook 1 of frame s, codebook 2 of frame s−1, codebook 3 of frame s−2 and codebook 4 of frame s−3. Each finer code is therefore predicted after the coarser codes of the same frame are known, at the cost of only 3 extra steps (T + 3 total).

The same codec-token idea now powers speech language models and real-time voice assistants: audio in → codec tokens → Transformer → codec tokens → audio out, with no separate ASR or TTS step.

Quiz

1.
EnCodec at 24 kHz produces 75 frames per second with 1024-entry codebooks. How many codebooks give 6 kbps?
2.
In residual vector quantization, what does the second quantizer encode?
3.
You raise MusicGen's guidance_scale from 3 to 10. What is most likely?
4.
How can AudioLDM be trained on audio that has no text captions?
5.
Why do modern audio generators work on codec tokens instead of raw samples?
Score: 0/5

References

  1. [1]
    SoundStream: An End-to-End Neural Audio Codec
    PaperZeghidour et al.2021arxiv.org
  2. [2]
    High Fidelity Neural Audio Compression
    PaperDéfossez et al.2022arxiv.org
    EnCodec.
  3. [3]
    AudioLM: a Language Modeling Approach to Audio Generation
    PaperBorsos et al.2022arxiv.org
  4. [4]
    Simple and Controllable Music Generation
    PaperCopet et al.2023arxiv.org
    MusicGen.
  5. [5]
    AudioLDM: Text-to-Audio Generation with Latent Diffusion Models
    PaperLiu et al.2023arxiv.org
  6. [6]
    Jukebox: A Generative Model for Music
    PaperDhariwal et al.2020arxiv.org
← Previous
Speech Synthesis: From Text to a Natural Voice
Next → · Multimodal, Video & 3D
Vision Transformers and CLIP