AI Wiki中文/EN

Text-to-speech: choosing words, sounds and timing

文本转语音

Trace a synthesis pipeline, resolve front-end ambiguities, train a duration model and challenge attention-based timing.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A short instruction can have more than one reading

Consider the invented test input Read 12.. Is 12 a quantity, pronounced “twelve,” or a sequence of identifiers, pronounced “one two”? The spelling read also has present and past pronunciations. A loudspeaker cannot resolve either choice. Those decisions must happen before the waveform reaches it.

Text-to-speech, or TTS, converts written input into spoken output. Its job includes selecting linguistic content, assigning pronunciation and timing, producing acoustic descriptions, and generating a waveform. These responsibilities can live in separate modules or be learned jointly; drawing a pipeline does not imply that every deployed system exposes the same interfaces. Flite’s language, lexicon and voice components offer a concrete modular example. Its “language” component is not an ASR language model that scores word sequences. Flite architecture

For a fixed set of announcements, a useful non-AI baseline is to record complete approved messages and select the appropriate recording. This preserves a speaker’s timing but cannot read arbitrary new text. A rule-and-lexicon front end extends coverage while making pronunciation decisions inspectable. A learned acoustic model addresses another part of the problem; adding one does not automatically repair an incorrect number reading.

Before the mathematics, review mel spectrograms and attention. Here we concentrate on the front end and duration, rather than rebuilding waveform synthesis.

Duration training and rounding change the frame count; equally concentrated attention can follow the wrong order.
Duration training and rounding change the frame count; equally concentrated attention can follow the wrong order.

Words, phones and frames use different clocks

Use the following as a conceptual decomposition. Input text is aa, normalized words are ww, pronunciation units are pp, acoustic frames are HH, and waveform samples are xx. Their lengths J,N,T,SJ,N,T,S need not match:

a⟶w1:J⟶p1:N⟶H1:T⟶x1:S,a\longrightarrow w_{1:J}\longrightarrow p_{1:N}\longrightarrow H_{1:T}\longrightarrow x_{1:S},

Normalization answers what the text means in this application. A digit string might name a quantity, date or telephone number. Pronunciation then maps the normalized words to sound units, using a lexicon and possibly rules for missing entries. The fixed Flite source checks token context and phone-number patterns; blindly reading every integer as a cardinal number would erase that distinction. Our example supports only a small declared subset. Fixed front-end source

An acoustic frame spans time, whereas a phone describes linguistic sound content. Duration alignment bridges them. Suppose AA is a nonnegative T×NT\times N attention matrix, with each row summing to one. Assign each acoustic frame to its most attended phone; ties in our program select the smallest index. The equations number phones from 1; the program and worked paths number them from 0:

πt=arg max⁡1≤i≤NAt,i,Di=∑t=1T1[πt=i],F(A)=1T∑t=1Tmax⁡iAt,i.\pi_t=\operatorname*{arg\,max}_{1\le i\le N}A_{t,i},\qquad D_i=\sum_{t=1}^{T}\mathbf1[\pi_t=i],\qquad F(A)=\frac1T\sum_{t=1}^{T}\max_i A_{t,i}.

FastSpeech uses teacher attention to derive durations, and selects an attention head using the concentration score FF. These are inferred training targets, not manually certified durations. A reversed one-hot path has the same focus score 1 as a correct forward path. Counting assigned frames also loses their ordering: the paths 0, 0, 1, 2, 2, 3 and 3, 2, 2, 1, 0, 0 produce the same durations. FastSpeech, section 3.3

Given a phone state hih_i and duration estimate did_i, a length regulator repeats the state. Our explicit rounding convention and zero-based frame offset are:

ci=⌊αdi+12⌋,bi=∑j<icj,h~bi+k=hi(0≤k<ci).c_i=\left\lfloor\alpha d_i+\tfrac12\right\rfloor,\qquad b_i=\sum_{j<i}c_j,\qquad \widetilde h_{b_i+k}=h_i\quad(0\le k<c_i).

The positive multiplier α\alpha changes the number of frames. Larger values generally make the utterance slower when the frame hop stays fixed. Rounding matters: multiplying [2, 2, 3, 1] by 0.5 and rounding halves upward gives [1, 1, 2, 1], not Python’s default ties-to-even result. A zero count removes a phone from the expanded sequence; repeated states alone do not create articulation or a waveform. Length regulation

To train something small enough to inspect, let XX contain nn rows of dd phone features, and let ww be a dd-element coefficient vector. We use an intercept, a vowel indicator and a pause indicator. With integer synthetic target durations DiD_i, minimize:

J(w)=1n∑i=1n(Xiw−log⁡(1+Di))2+λ∥w∥22.J(w)=\frac1n\sum_{i=1}^n\left(X_iw-\log(1+D_i)\right)^2+\lambda\|w\|_2^2.

Here λ\lambda is a nonnegative regularization strength. Applying the chain rule to the squared residual gives twice the residual times its feature row; adding the rows and differentiating the squared norm yields:

∇wJ=2nX⊤(Xw−log⁡(1+D))+2λw,w+=w−η∇wJ.\nabla_w J=\frac2n X^\top\left(Xw-\log(1+D)\right)+2\lambda w,\qquad w^+=w-\eta\nabla_wJ.

This is a linear regressor with a log1p target, chosen to accommodate zero durations. FastSpeech instead describes a convolutional duration predictor and a log-duration training objective. Our regression is a teaching substitute, not that predictor. The inference-only clipping policy confines each estimate to 0–32 frames:

d^i=exp⁡ ⁣(clip⁡(Xiw,0,log⁡33))−1.\widehat d_i=\exp\!\left(\operatorname{clip}(X_iw,0,\log33)\right)-1.

The gradient above belongs to the unclipped training objective. Treating the clipped output as if it had that same derivative would describe a different model. Training costs O(nd)O(nd) per update, alignment counting costs O(TN)O(TN), and expansion costs O(d∑ici)O(d\sum_i c_i) when states have dimension dd.

Train durations for nine declared pronunciation units

Run the complete program with Python 3.12 and NumPy 1.26.4. The lexicon uses a small set of unstressed pronunciation labels; it is not a full pronunciation dictionary. read_sense supplies the homograph choice. The program rejects unknown words instead of silently inventing pronunciations. Normalization covers some words, such as “twenty,” that this tiny lexicon does not cover; the two stages have separate failure boundaries.

Inputs allow short ASCII text, one- or two-digit tokens and a few punctuation marks. Decimals, grouped numbers, mixed letter-digit tokens and undeclared language forms fail explicitly. PAUSE is a toy punctuation policy. The model fits vowel, consonant and pause targets 4, 2 and 6 frames on the same nine-unit example; it produces no spoken waveform.

"""Original bounded TTS front-end and duration components; no speech waveform.

Small declared English vocabulary, supplied homograph sense, log1p duration
regression and explicit half-up length rounding. Not Flite or FastSpeech.
"""
import json
import re
import numpy as np

ONES='zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen'.split()
TENS=['','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
LEXICON={'call':['K','AO','L'],'one':['W','AH','N'],'two':['T','UW'],'three':['TH','R','IY'],
         'twelve':['T','W','EH','L','V'],'zero':['Z','IY','R','OW'],'oh':['OW']}


def normalize(text,number_mode='cardinal'):
    if type(text) is not str or not 1<=len(text)<=200 or number_mode not in ('cardinal','digits'):raise ValueError('Use bounded text and an explicit number mode')
    if not re.fullmatch(r'[A-Za-z0-9 ,.!?]+',text) or re.search(r'\d[.,]\d|[A-Za-z]\d|\d[A-Za-z]',text):raise ValueError('Unsupported text, decimal, grouped number or mixed token')
    result=[]
    for token in re.findall(r'[A-Za-z]+|\d+|[,!.?]',text.lower()):
        if token.isdigit():
            if len(token)>2:raise ValueError('Only one or two digit tokens are supported')
            if number_mode=='digits':result.extend(ONES[int(c)] for c in token);continue
            if len(token)>1 and token[0]=='0':raise ValueError('Leading zeros require an explicit digit reading')
            n=int(token);result.extend([ONES[n]] if n<20 else [TENS[n//10]]+([ONES[n%10]] if n%10 else []))
        else:result.append(token)
    if not result or len(result)>40:raise ValueError('Empty or excessive token sequence')
    return result


def pronounce(words,read_sense=None):
    if not isinstance(words,(list,tuple)) or not 1<=len(words)<=40:raise ValueError('Use a bounded token sequence')
    if read_sense not in (None,'present','past'):raise ValueError('Unknown reading sense')
    phones=[];word_index=[]
    for i,word in enumerate(words):
        if type(word) is not str:raise ValueError('Each token must be a string')
        if word in ',.!?' and len(word)==1:unit=['PAUSE']
        elif word=='read':
            if read_sense is None:raise ValueError('Choose present or past for the homograph read')
            unit=['R','IY' if read_sense=='present' else 'EH','D']
        elif word in LEXICON:unit=LEXICON[word]
        else:raise ValueError('Word absent from the declared toy lexicon: '+str(word))
        phones.extend(unit);word_index.extend([i]*len(unit))
    if len(phones)>64:raise ValueError('Too many phone units')
    return dict(phones=phones,word_index=word_index)


def duration_labels(attention):
    a=np.asarray(attention)
    if a.dtype.kind not in 'fiu' or a.ndim!=2 or not 1<=a.shape[0]<=128 or not 1<=a.shape[1]<=32 or not np.isfinite(a).all() or np.any(a<0) or not np.allclose(a.sum(axis=1),1,atol=1e-12,rtol=0):raise ValueError('Use a finite row-stochastic alignment')
    path=a.argmax(axis=1);counts=np.bincount(path,minlength=a.shape[1])
    return dict(durations=counts,path=path,focus=float(a.max(axis=1).mean()),backward_steps=int(np.sum(np.diff(path)<0)),uncovered=np.flatnonzero(counts==0))


def duration_loss(features,weights,durations,penalty=.01):
    x=np.asarray(features);w=np.asarray(weights);d=np.asarray(durations)
    if x.dtype.kind not in 'fiu' or w.dtype.kind not in 'fiu' or d.dtype.kind not in 'iu' or x.ndim!=2 or not 1<=x.shape[0]<=128 or not 1<=x.shape[1]<=16 or w.shape!=(x.shape[1],) or d.shape!=(len(x),):raise ValueError('Invalid duration regression shapes')
    if not np.isfinite(x).all() or not np.isfinite(w).all() or np.any((x < -8)|(x > 8)) or np.any((w < -8)|(w > 8)) or np.any((d<0)|(d>32)) or type(penalty) not in (int,float) or not 0<=penalty<=1:raise ValueError('Invalid regression values')
    x=x.astype(float);w=w.astype(float);residual=x@w-np.log1p(d)
    loss=np.mean(residual**2)+penalty*np.sum(w*w);gradient=2*x.T@residual/len(x)+2*penalty*w
    return dict(loss=float(loss),gradient=gradient,predicted=np.expm1(np.clip(x@w,0,np.log(33))))


def fit_durations(features,durations,steps=150,rate=.05):
    x=np.asarray(features)
    if x.ndim!=2 or type(steps) is not int or not 0<=steps<=500 or type(rate) not in (int,float) or not 0<rate<=.1:raise ValueError('Invalid fit settings')
    w=np.zeros(x.shape[1]);history=[]
    for _ in range(steps):
        r=duration_loss(x,w,durations);history.append(r['loss']);w-=rate*r['gradient']
    r=duration_loss(x,w,durations);history.append(r['loss'])
    return dict(weights=w,history=history,predicted=r['predicted'])


def expand(states,durations,alpha=1.):
    h=np.asarray(states);d=np.asarray(durations)
    if h.dtype.kind not in 'fiu' or h.ndim!=2 or not 1<=len(h)<=64 or not 1<=h.shape[1]<=16 or not np.isfinite(h).all() or np.any((h < -8)|(h > 8)) or d.shape!=(len(h),) or d.dtype.kind not in 'fiu' or not np.isfinite(d).all() or np.any((d<0)|(d>32)):raise ValueError('Invalid states/durations')
    if type(alpha) not in (int,float) or not .1<=alpha<=4:raise ValueError('Invalid duration multiplier')
    counts=np.floor(d.astype(float)*alpha+.5).astype(int)
    if counts.sum()>512:raise ValueError('Expanded sequence is too long')
    ids=np.repeat(np.arange(len(h)),counts);bounds=np.r_[0,np.cumsum(counts)]
    return dict(values=h[ids],phone_indices=ids,counts=counts,boundaries=bounds)


def demo():
    words=normalize('Read 12.');phones=pronounce(words,'present');n=len(phones['phones'])
    vowel=np.array([p in ['IY','EH','UW','AH','AO','OW'] for p in phones['phones']],dtype=float)
    boundary=np.array([p=='PAUSE' for p in phones['phones']],dtype=float);features=np.column_stack([np.ones(n),vowel,boundary])
    target=np.where(boundary,6,np.where(vowel,4,2));learned=fit_durations(features,target)
    states=np.column_stack([vowel,boundary]);normal=expand(states,learned['predicted']);fast=expand(states,learned['predicted'],.5)
    original=duration_labels(np.eye(4)[[0,0,1,2,2,3]]);reverse=duration_labels(np.eye(4)[[3,2,2,1,0,0]])
    paper=expand(np.eye(4),[2,2,3,1],.5)
    return dict(cardinal=words,digits=normalize('Read 12.',number_mode='digits'),present=phones,past=pronounce(words,'past'),
        training=dict(first=learned['history'][0],last=learned['history'][-1],weights=learned['weights'].tolist(),history=learned['history'][::15],predicted=learned['predicted'].tolist()),
        normal=dict(counts=normal['counts'].tolist(),boundaries=normal['boundaries'].tolist(),phone_indices=normal['phone_indices'].tolist()),
        fast=dict(counts=fast['counts'].tolist(),length=len(fast['values'])),
        alignments={name:dict(focus=a['focus'],durations=a['durations'].tolist(),backward_steps=a['backward_steps'],path=a['path'].tolist()) for name,a in [('forward',original),('reverse',reverse)]},
        half_up=dict(counts=paper['counts'].tolist(),indices=paper['phone_indices'].tolist()),
        missing_phone=expand([[1],[2]],[.4,2],.5)['counts'].tolist())


if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

With 150 updates of size 0.05, the objective decreases from about 1.800982 to 0.023390. The rounded default durations total 25 frames; using multiplier 0.5 yields 12. These are frame counts, not seconds: multiplying by an explicitly selected acoustic hop would supply a time interpretation. The learned pause is about 4.83 frames rather than exactly 6 because the objective is regularized and training is finite.

Inspect both alignment outputs. Each has focus 1 and the same counts, but the reversed path has three backward steps. The missing_phone example returns [0, 1], exposing a deletion caused by scaling and rounding. Neither outcome should be hidden behind a fluent-sounding final recording.

A good waveform can still say the wrong thing

This example separates four checks. First, compare normalized words with the intended reading. Second, inspect pronunciation and missing lexicon entries. Third, examine alignment order, coverage and durations. Finally, evaluate synthesized audio if a waveform stage is added. A single duration loss cannot replace these different observations.

For an expanded project, declare a held-out text set containing ambiguous numbers, unfamiliar names, punctuation and longer sentences. Record linguistic errors separately from duration error. Measure first-output latency and total synthesis time under stated hardware and output length; a fast front end does not establish real-time performance of the full system. Listening tests also need a defined protocol and listeners. No such speech-quality study is performed by this synthetic fit.

Prosody includes stress, intonation and phrasing, not merely a global speed multiplier. The hand-written vocabulary and supplied homograph sense deliberately leave those tasks unresolved. More expressive models can change where the decisions occur, but they still need evaluation of the resulting spoken content.

Check the reading before trusting the sound

  1. A number changes role. An application treats 12 as two identifier digits. Which stage must change, and can retraining the duration regressor fix a cardinal reading?

Answer: Normalization must select “one two” rather than “twelve.” Changing durations alters timing of the chosen phones; it does not replace the underlying words. Our digits mode exposes that application decision.

  1. A regulator hand calculation. Expand four states with durations [2, 2, 3, 1] and multiplier 0.5 using the program’s rounding. How many frames result?

Answer: Scaled durations [1, 1, 1.5,0.5] become [1, 1, 2, 1]. The result has 5 frames with state indices 0, 1, 2, 2, 3. Exact scaling of the original 8-frame total would give 4, but rounding is performed per phone.

  1. A convincing attention plot. Every attention row has one entry 1; selected phone indices run in reverse. What does focus report, and what additional check reveals the problem?

Answer: Focus reports 1 because every row maximum is 1. Inspect consecutive selected positions: decreases reveal backward movement. Count coverage as well, since a forward-looking but incomplete path can still skip phones.

  1. A disappearing phone. A predicted duration is 0.4 and the multiplier is 0.5. Should the application automatically claim a correct faster reading?

Answer: The scaled value 0.2 rounds to 0, removing that phone. An application must define whether to reject such settings, enforce minimum durations or permit particular deletions. Our example permits deletion to expose the boundary; none of these policies can be inferred from the low regression loss.

Read the module boundary as carefully as the model name

Flite’s 2001 paper supports the modular language/lexicon/voice account; its fixed source gives a concrete context-sensitive front end. FastSpeech’s 2019 duration regulator makes an alternative timing interface explicit. We read the relevant architectural and duration sections, not every benchmark. The original code here borrows no upstream implementation or voice database.

Continue by comparing a text-to-acoustic decoder with a waveform generator. Ask which representation crosses the boundary, where timing is chosen, and which failures each evaluation can actually detect.

Make a prediction, then check

Every attention row is one-hot, but the selected phoneme indices run backward. What follows?

Choose one answer

Learning objectives

  • Separate text normalization, pronunciation, timing and waveform generation.
  • Derive and train a bounded log-duration regression model.
  • Explain why concentrated attention does not guarantee correct order.
  • Evaluate linguistic errors separately from speed and audio quality.

Prerequisites & connections

Explore related knowledge →

References

  1. Flite: a small fast run-time synthesis engine
    Alan W Black; Kevin A. Lenzo · 2001
  2. FastSpeech: Fast, Robust and Controllable Text to Speech
    Yi Ren; Yangjun Ruan; Xu Tan; Tao Qin; Sheng Zhao; Zhou Zhao; Tie-Yan Liu · 2019
  3. Flite English text processing at6c9f20d
    Flite contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked Flite component/context boundaries and FastSpeech duration/focus assumptions; original log1p linear regression, zero-duration and half-up behavior. Six paired equations, four explained exercises and nine-unit actual training. The program is a narrow front end and timing model, not full speech synthesis.

  • Normalization/cardinal versus digit reading, supplied homograph sense, declared lexicon scope, log1p gradient and frame expansion verified. Focus1 reverse path retains counts but has three backward moves;25 versus12 rounded frames and deletion0 tested.
  • Four computed SVGs bind exact bilingual MDX. The four-topic group passed14 numeric/encoding checks and24 isolated language/width cases with four fallback fonts; eight representative actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.