PROMETHEUS OS
NATIVE AI OPERATING SYSTEM
[INIT] Prometheus OS loading...
[CORE] Neural interface initializing...
[AI] LLM router connecting...
[MEM] Memory graph loading...
[AGT] Agent chains on standby...
[SEC] Security protocols active...
[NET] Provider mesh established...
[UI] Workspace rendering...
[DONE] All systems nominal.
Welcome to PROMETHEUS OS.
READY · OFFLINE · SECURE · PRIVATE
🎨 THEME ENGINE
PROMETHEUS OS · 23 THEMES
Trial version: Dark + Light themes only.
Full theme access with PROMETHEUS OS license.
Dark theme active
Experience all 23 themes in PROMETHEUS OS

Audio, Voice and Music Generation

Advanced 16 min· 5 exercises

Explain how neural codecs, TTS architectures, voice cloning, music generators and real-time voice models work, compute codec bitrates and token rates, and evaluate audio systems with MOS and objective metrics.

By the end of this lesson you will be able to
  • Explain how neural audio codecs use residual vector quantization to turn audio into discrete tokens, and compute their bitrate and token rate.
  • Compare two-stage, codec language model and diffusion or flow-matching TTS architectures.
  • Identify the consent, fraud and safety risks of voice cloning and the controls that mitigate them.
  • Describe the main approaches to music generation and their trade-offs.
  • Compute a MOS with a confidence interval and choose appropriate objective metrics for speech and music.
  • Compare cascaded and speech-to-speech architectures for real-time voice agents and estimate their latency budgets.

Before this: Generative Models: The Big Picture, Speech and Audio AI: Recognition, Synthesis and Real-Time Voice, Transformers: A Deep Dive

Synthetic speech now reads audiobooks, voices navigation and customer-service agents, dubs video into other languages and gives people who have lost their voice a way to speak in something close to their own. Music generators produce full songs from a text prompt. The same technology also enables voice-clone fraud. This lesson explains how modern audio generation works, from codecs that turn sound into tokens to real-time conversational voice models, and how to evaluate and deploy it responsibly.

Why audio is hard

Audio is a long, dense signal. Speech is commonly sampled at 16 to 24 kHz and music at 44.1 or 48 kHz, so ten seconds of 24 kHz audio is 240,000 numbers. Generating each sample autoregressively, as WaveNet (van den Oord et al., 2016) did, produced excellent quality but was slow. Humans are also unforgiving listeners: small phase errors sound metallic, tiny timing glitches sound like clicks, and wrong prosody (rhythm, stress and intonation) makes speech sound robotic even when every word is right.

The field's answer has been to change the representation before generating. There are two main choices:

  1. Mel spectrograms: a time-frequency picture of the sound with frequencies warped to the perceptual mel scale, m=2595log⁡10(1+f/700)m = 2595 \log_{10}(1 + f/700), where ff is frequency in Hz (by construction, 1000 Hz maps to about 1000 mel). A vocoder converts the spectrogram back to a waveform.
  2. Neural codec tokens: a learned compressor turns audio into a short sequence of discrete integers, which a language model can generate just like text.

Neural audio codecs and audio tokens

A neural audio codec is an autoencoder with a quantized bottleneck. SoundStream (Zeghidour et al., 2021) and EnCodec (Défossez et al., 2022) established the standard recipe:

  • A convolutional encoder turns the waveform into a sequence of latent vectors at a low frame rate (EnCodec at 24 kHz uses 75 frames per second).
  • A residual vector quantizer (RVQ) turns each latent vector into several integer codes.
  • A decoder reconstructs the waveform, trained with reconstruction losses on waveform and spectrograms plus adversarial (GAN) discriminator losses, which make the output sound sharp rather than muffled.

Residual vector quantization

A single codebook of KK entries can only represent KK distinct vectors, too few for high fidelity. RVQ uses NqN_q codebooks in sequence. The first quantizes the latent zz; each later stage quantizes what the previous stages missed:

r0=z,ki=arg⁡min⁡k∥ri−1−ck(i)∥,ri=ri−1−cki(i),z^=∑i=1Nqcki(i)r_0 = z, \qquad k_i = \arg\min_{k} \left\| r_{i-1} - c^{(i)}_k \right\|, \qquad r_i = r_{i-1} - c^{(i)}_{k_i}, \qquad \hat z = \sum_{i=1}^{N_q} c^{(i)}_{k_i}

where ck(i)c^{(i)}_k is entry kk of codebook ii, and kik_i is the integer token emitted by stage ii. Coarse codebooks capture the gist (speaker, phonetic content), fine ones add detail. A useful property is bitrate scalability: drop the last codebooks and you still get intelligible, lower-quality audio.

Worked example: bitrate and token rate. EnCodec at 24 kHz uses codebooks of 1,024 entries, so each code carries log⁡21024=10\log_2 1024 = 10 bits. At 75 frames per second with 8 codebooks:

75×8×10=6,000 bits/s=6 kbps75 \times 8 \times 10 = 6{,}000 \text{ bits/s} = 6 \text{ kbps}

compared with 24,000×16=38424{,}000 \times 16 = 384 kbps for raw 16-bit audio, a 64× reduction. For a language model, the cost is the token count: 75×8=60075 \times 8 = 600 tokens per second, so 10 seconds is 6,000 tokens. That is still long, which is why models use tricks: predict the first (coarse) codebook autoregressively and the rest in parallel or with a smaller model; interleave codebooks with a delay pattern so one transformer step emits all codebooks with offsets (MusicGen, Copet et al., 2023); or use lower frame rates (newer speech codecs operate around 12.5 frames per second).

Semantic vs acoustic tokens. AudioLM (Borsos et al., 2022) combined two token types: semantic tokens from a self-supervised speech model (capturing content and long-range structure) and acoustic tokens from a codec (capturing voice and recording detail). Generating semantic tokens first and acoustic tokens second improved long-range coherence. Several later codecs distill semantic information directly into their first codebook.

Text-to-speech (TTS) architectures

Two-stage pipelines

Classic neural TTS splits the job:

  1. Text front end: normalize text ("Dr." to "doctor", "£5" to "five pounds"), convert to phonemes (grapheme-to-phoneme), and sometimes predict prosody features.
  2. Acoustic model: phonemes to mel spectrogram. Tacotron 2 (Shen et al., 2018) used an attention-based sequence-to-sequence model; FastSpeech 2 (Ren et al., 2020) is non-autoregressive, predicting durations, pitch and energy explicitly, which made it faster and more robust (no skipped or repeated words from attention failures).
  3. Vocoder: mel to waveform. HiFi-GAN (Kong et al., 2020) is a GAN vocoder that runs much faster than real time.

VITS (Kim et al., 2021) merged these stages into one end-to-end model combining a VAE, a normalizing flow and adversarial training.

Codec language models

VALL-E (Wang et al., 2023) reframed TTS as language modeling: condition a transformer on phonemes and the codec tokens of a short acoustic prompt (about 3 seconds of the target speaker) and generate codec tokens that continue in that voice. This gave zero-shot voice cloning: no fine-tuning per speaker. It also inherits language-model failure modes: occasional repeated or skipped words, and sensitivity to sampling settings.

Diffusion and flow-matching TTS

Another family generates mel spectrograms or continuous codec latents with diffusion or flow matching, often non-autoregressively over the whole utterance with a separately predicted total duration. Voicebox (Le et al., 2023) used flow matching with speech infilling as its training task, which supports editing a word in the middle of a recording. Many current open TTS systems combine an autoregressive model for content and timing with a flow-matching stage for acoustic detail.

Comparison

ApproachStrengthsWeaknesses
Two-stage (acoustic model + vocoder)Robust, controllable, fastLess natural prosody, needs per-voice training for cloning
Codec language modelZero-shot cloning, expressive, unified with LLMsCan hallucinate or skip words; sequential decoding latency
Diffusion / flow matchingHigh quality, parallel, supports infilling and editingMultiple solver steps; duration must be predicted

Zero-shot cloning from seconds of audio means anyone with a public video can have their voice imitated. Documented harms include impersonation scams targeting family members and businesses, bypassing voice-based authentication, harassment and non-consensual content, and political disinformation. Responsible practice:

  • Consent and verification. Clone only voices with explicit, recorded consent. Some providers require the speaker to read a randomly generated verification sentence, which a pre-recorded clip cannot satisfy.
  • Policy controls. Block cloning of public figures, keep audit logs, and rate-limit.
  • Provenance. Embed inaudible watermarks in generated audio (for example Meta's AudioSeal or Google's SynthID for audio) and attach C2PA content credentials where formats allow. Watermarks help only for content from cooperating generators.
  • Organizational defenses. Stop treating voice as proof of identity: use call-backs to known numbers, shared passphrases and multi-person approval for payments. The deepfakes lesson covers this in depth.
  • Legal exposure. Laws on likeness rights, fraud and AI disclosure vary by jurisdiction and are changing; check current rules before shipping a voice product.

Music generation

Music is harder than speech: longer coherent structure (verses, choruses, key and tempo), polyphony, stereo, wide bandwidth and lyrics. Approaches mirror the rest of the field:

  • Token language models over codecs. OpenAI's Jukebox (Dhariwal et al., 2020) used hierarchical VQ-VAE tokens with transformers. MusicLM (Agostinelli et al., 2023) extended AudioLM with text conditioning through a joint music-text embedding. MusicGen (Copet et al., 2023) is a single-stage transformer over EnCodec tokens using the delay pattern, conditioned on text and optionally a melody.
  • Latent diffusion. Stable Audio (Evans et al., 2024) runs diffusion in a learned audio latent space and conditions on start time and total duration so outputs can be a requested length.
  • Symbolic generation. Generating MIDI or scores with a sequence model, then rendering with instruments. It offers precise editability, but quality depends on the rendering.

Commercial song generators with vocals are widely used as of November 2026 (Google's Lyria is one example that carries SynthID watermarks), but training on copyrighted recordings is a contested legal issue, and some licensing arrangements between AI music companies and rights holders are evolving. For commercial use, check the provider's license terms, training-data disclosures and whether outputs can be claimed as your copyright.

Evaluation

Mean opinion score (MOS)

The reference method is listening tests. In a MOS test (ITU-T Recommendation P.800 describes the absolute category rating procedure), listeners rate each sample from 1 (bad) to 5 (excellent), and scores are averaged. Variants: CMOS (comparative, rate B relative to A from −3 to +3), SMOS (speaker similarity), and MUSHRA for finer quality distinctions with hidden references and anchors.

Worked example. Ten ratings for one system: 4, 5, 4, 3, 4, 5, 4, 4, 3, 4.

  1. Mean: 40/10=4.040 / 10 = 4.0.
  2. Deviations from 4: 0, 1, 0, −1, 0, 1, 0, 0, −1, 0; squared sum =4= 4; sample variance =4/9=0.444= 4/9 = 0.444; standard deviation s=0.667s = 0.667.
  3. 95% confidence half-width with a tt critical value of 2.262 (9 degrees of freedom): 2.262×0.667/10=0.4772.262 \times 0.667 / \sqrt{10} = 0.477.
  4. Report MOS =4.00±0.48= 4.00 \pm 0.48.

If a competing system scored 4.20±0.454.20 \pm 0.45 from a similar test, the intervals overlap heavily and you cannot claim it is better. Real studies use many more listeners and utterances, randomize order, include hidden references, screen inattentive raters, and account for per-listener bias with mixed-effects models. MOS values are not comparable across different tests or listener pools.

Objective metrics

  • Intelligibility: transcribe the output with a strong speech recognizer and compute word error rate against the input text.
  • Speaker similarity: cosine similarity between speaker-verification embeddings of the prompt and the output.
  • Predicted MOS: neural MOS predictors (UTMOS and similar) are useful for regression testing but can be gamed.
  • Music: Fréchet Audio Distance (FAD), an FID analogue on audio embeddings, and CLAP score, a CLIP-score analogue for text-audio alignment.
  • Latency: time to first audio and real-time factor (processing time divided by audio duration; below 1 means faster than real time).

Real-time voice models

Conversational voice agents need first audio within a few hundred milliseconds. There are two architectures.

Cascaded pipelines chain speech recognition, a text LLM and streaming TTS. They are modular, easy to debug, and let you swap components, but lose paralinguistic information (tone, emotion, laughter) at the ASR step, and latencies add up. A rough budget: end-of-speech detection 200 to 500 ms, ASR finalization 100 to 300 ms, LLM time to first token 200 to 500 ms, TTS time to first audio 100 to 300 ms, so 0.6 to 1.6 s in total unless each stage streams aggressively.

Speech-to-speech (native audio) models consume and emit audio tokens directly within one model. Moshi (Défossez et al., 2024, from Kyutai) is a published example of a full-duplex design: it models the user's and its own audio streams simultaneously, so it can listen while speaking and handle interruptions and back-channels ("mm-hmm"), and it predicts aligned text tokens as an "inner monologue" to keep content coherent. Several commercial providers offer speech-to-speech APIs as of November 2026; their names and capabilities change quickly, so check current documentation. Trade-offs: lower latency and richer prosody, but harder to inspect, constrain and evaluate than a text pipeline, and tool use and guardrails must operate on audio-native outputs.

Code: residual vector quantization from scratch

This builds a 4-stage RVQ with k-means codebooks on stand-in latent vectors (in a real codec, a neural encoder produces them and codebooks are learned jointly). It shows how each stage lowers the error and how tokens are produced.

import numpy as np
from sklearn.cluster import KMeans

rng = np.random.default_rng(0)
# Stand-in for encoder outputs: 5,000 frames of 8-dim latent vectors
latents = rng.normal(size=(5000, 8)) @ rng.normal(size=(8, 8))

def train_rvq(x, n_stages=4, codebook_size=64):
    codebooks, residual = [], x.copy()
    for _ in range(n_stages):
        km = KMeans(n_clusters=codebook_size, n_init=1, random_state=0).fit(residual)
        codebooks.append(km.cluster_centers_)
        residual = residual - km.cluster_centers_[km.labels_]
    return codebooks

def encode(x, codebooks):
    codes, residual = [], x.copy()
    for cb in codebooks:
        d = ((residual[:, None, :] - cb[None]) ** 2).sum(-1)
        idx = d.argmin(1)
        codes.append(idx)
        residual = residual - cb[idx]
    return np.stack(codes, 1)            # (frames, n_stages) integer tokens

def decode(codes, codebooks):
    return sum(cb[codes[:, i]] for i, cb in enumerate(codebooks))

cbs = train_rvq(latents)
codes = encode(latents, cbs)
for k in range(1, 5):
    err = ((latents - decode(codes[:, :k], cbs[:k])) ** 2).mean()
    print(f"{k} codebooks: MSE {err:.3f}, bits/frame {k * 6}")

With 64-entry codebooks each code is 6 bits. On one run the mean-squared error fell from about 1.64 with one codebook to about 0.10 with four, illustrating bitrate scalability. The codes array is exactly what an audio language model would be trained to predict.

Common pitfalls

  • Judging by cherry-picked demos. TTS and music systems vary a lot by seed and prompt. Evaluate on a fixed, diverse set of texts including numbers, names, abbreviations, long sentences and other languages.
  • Ignoring text normalization. Many "model errors" are front-end errors: dates, currencies, acronyms and homographs ("read", "lead").
  • Single-number MOS claims. Without confidence intervals, listener counts and test design, a MOS is not evidence. Never compare MOS across separate studies.
  • Latency measured end to end only once. Measure each stage, measure the 95th percentile not just the mean, and test under realistic network conditions.
  • Treating consent as a checkbox. Store proof of consent for each cloned voice, allow revocation, and prevent use of uploaded voices outside the consented purpose.

In practice

For a product voice, teams typically license a TTS API or fine-tune an open model on a few hours of consented studio recordings, build a text-normalization layer with domain lexicons, and run regression tests that combine ASR word error rate, speaker similarity and periodic listening tests. For conversational agents, start with a cascaded pipeline when you need tools, logging and guardrails, and evaluate speech-to-speech models when natural turn-taking matters most. For music, check licensing first. In every case, watermark or label generated audio and design business processes so a convincing voice is never sufficient authorization.

Key takeaways

  • Modern audio generation works on compressed representations: mel spectrograms with vocoders, or discrete tokens from neural codecs.
  • Residual vector quantization stacks codebooks that each encode the previous stage's error, giving scalable bitrate and token streams a transformer can model.
  • TTS has moved from two-stage acoustic-model-plus-vocoder pipelines to codec language models and flow-matching models capable of zero-shot voice cloning.
  • Voice cloning demands explicit consent, provenance marking, and business processes that never treat a voice as proof of identity.
  • MOS listening tests remain the reference for quality but need confidence intervals and careful design; WER, speaker similarity, FAD and latency complement them.
  • Real-time voice agents choose between modular cascaded pipelines and lower-latency, full-duplex speech-to-speech models.

Terms in this lesson

Neural audio codec
An autoencoder with a quantized bottleneck that compresses audio into discrete codes and reconstructs it, trained with reconstruction and adversarial losses.
Residual vector quantization (RVQ)
Quantization with a sequence of codebooks in which each stage encodes the residual error left by the previous stages.
Vocoder
A model that converts an intermediate acoustic representation, such as a mel spectrogram, into a waveform.
Mel spectrogram
A time-frequency representation of audio with the frequency axis warped to the perceptual mel scale.
Zero-shot voice cloning
Generating speech in a new speaker's voice from a short reference recording without training on that speaker.
Mean opinion score (MOS)
The average of listener ratings on a 1 to 5 quality scale, used as a subjective measure of audio quality.
Full-duplex
A conversational model that can listen and speak at the same time, handling interruptions and overlaps.
Real-time factor
Processing time divided by the duration of the audio produced; values below 1 mean faster than real time.

Check your understanding

  1. 1.

    A codec runs at 50 frames per second with 4 codebooks of 2,048 entries each. What is its bitrate?

  2. 2.

    What does each later stage in residual vector quantization encode?

  3. 3.

    A bank's phone channel lets customers authorize transfers after voice recognition. What is the strongest mitigation against voice-clone fraud?

  4. 4.

    System A has MOS 3.90 with a 95% interval of plus or minus 0.30; System B has 4.05 plus or minus 0.28, from the same test. What can you conclude?

  5. 5.

    Your voice agent needs tool calls, auditable transcripts and strict content guardrails, and about one second of latency is acceptable. Which architecture should you start with?

Exercises

Work each problem before opening the solution.

  1. Exercise 1Core

    A codec operates at 24 kHz with 75 frames per second and 1,024-entry codebooks. Compute the bitrate with 2, 4, 16 and 32 codebooks, and the number of tokens a language model must generate for a 30-second clip at 8 codebooks.

    Show solution

    Each code is 10 bits; bitrate =75×Nq×10= 75 \times N_q \times 10.

    • 2 codebooks: 1.5 kbps
    • 4: 3 kbps
    • 16: 12 kbps
    • 32: 24 kbps

    Tokens for 30 s at 8 codebooks: 75×8×30=18,00075 \times 8 \times 30 = 18{,}000 tokens.

  2. Exercise 2Core

    Compute the MOS and a 95% confidence interval for ratings 5, 4, 4, 5, 3, 4, 5, 4 (use t=2.365t = 2.365 for 7 degrees of freedom).

    Show solution

    Sum =34= 34, n=8n = 8, mean =4.25= 4.25.

    Deviations: 0.75, −0.25, −0.25, 0.75, −1.25, −0.25, 0.75, −0.25. Squares: 0.5625 ×3 = 1.6875; 0.0625 ×4 = 0.25; 1.5625. Sum =3.5= 3.5. Variance =3.5/7=0.5= 3.5/7 = 0.5; s=0.7071s = 0.7071.

    Half-width =2.365×0.7071/8=2.365×0.25=0.591= 2.365 \times 0.7071/\sqrt{8} = 2.365 \times 0.25 = 0.591.

    MOS =4.25±0.59= 4.25 \pm 0.59. Eight ratings is far too few for a real decision.

  3. Exercise 3Core

    Write Python that computes word error rate (WER) between a reference transcript and an ASR transcript of TTS output, using word-level edit distance. Test it on reference 'the meeting is at ten thirty' and hypothesis 'the meeting is at 10 30'.

    Show solution
    def wer(ref, hyp):
        r, h = ref.split(), hyp.split()
        d = [[0] * (len(h) + 1) for _ in range(len(r) + 1)]
        for i in range(len(r) + 1):
            d[i][0] = i
        for j in range(len(h) + 1):
            d[0][j] = j
        for i in range(1, len(r) + 1):
            for j in range(1, len(h) + 1):
                cost = 0 if r[i - 1] == h[j - 1] else 1
                d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
        return d[len(r)][len(h)] / len(r)
    
    print(wer("the meeting is at ten thirty", "the meeting is at 10 30"))
    

    Output: two substitutions over six reference words, 2/6=0.3332/6 = 0.333. This illustrates why you must normalize both strings (numbers to words or vice versa) before computing WER; otherwise formatting differences masquerade as errors.

  4. Exercise 4Challenge

    Design a consent and safety process for a product that lets users create a cloned voice of themselves for narrating their own videos. Cover enrollment, ongoing use, misuse detection and revocation.

    Show solution

    Enrollment: authenticate the account; require the speaker to record a randomly generated consent statement live ("I, [name], consent to … on [date] …") in-session so a pre-recorded or scraped clip cannot pass; verify the consent recording matches the training audio by speaker similarity; store the consent artifact, timestamp and terms version.

    Scope limits: bind each voice to its owner's account only; no sharing or export of the voice model; block cloning when the enrollment voice matches a list of public figures; apply content policies to text sent for synthesis (no impersonation of others, fraud scripts or harassment).

    Provenance: watermark all generated audio and attach C2PA credentials on exported video; log every synthesis request with text hash and account.

    Misuse detection: rate-limit; flag requests mentioning payments, passwords or emergencies; provide a public reporting channel and a watermark-check tool for platforms and victims.

    Revocation: a one-click delete that removes the voice model and stops all synthesis, honored within a stated time; delete training audio per the retention policy; keep minimal audit records as required by law.

  5. Exercise 5Challenge

    Estimate end-to-end latency (median) for a cascaded voice agent with: voice-activity end-of-turn detection 300 ms, streaming ASR finalization 150 ms, LLM time to first token 350 ms, the TTS needs the first 8 tokens before it starts (LLM produces 50 tokens/s after the first), TTS time to first audio 150 ms, and 60 ms network overhead each way. Then propose changes that together bring it under 800 ms.

    Show solution

    LLM: first token at 350 ms, 7 more tokens at 20 ms each = 140 ms, so 490 ms until 8 tokens exist.

    Total =60+300+150+490+150+60=1,210= 60 + 300 + 150 + 490 + 150 + 60 = 1{,}210 ms.

    Changes (each with its effect):

    1. Start TTS after the first 3 tokens or the first phrase boundary: LLM wait drops to 350+40=390350 + 40 = 390 ms (saves 100 ms).
    2. Use a semantic end-of-turn model that predicts turn completion, shortening VAD silence to 150 ms (saves 150 ms), and speculatively start the LLM on partial ASR (overlap saves about 150 ms of ASR).
    3. Co-locate services to cut network to 20 ms each way (saves 80 ms).

    With all three: 1,210−100−150−150−80=7301{,}210 - 100 - 150 - 150 - 80 = 730 ms. Alternatively, a speech-to-speech model removes the ASR and TTS hand-offs entirely.

Further reading

Go further

Sources

Fact-checked and last reviewed 2026-11-05

Stay in the loop
Prometheus OS™ · Native AI OS · Built for the future © 2025 - 2026