AI Wiki中文/EN

文本转语音:先决定读什么,再决定怎样读

Text-to-speech

梳理合成流程,处理前端歧义,实际训练时长模型,并检验注意力时长的局限。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

一句短指令,也可能有几种读法

看一个虚构测试输入:Read 12.。12是数量,要读成“twelve”,还是一串编号,要读成“one two”?拼写read本身也有现在时和过去时的两种发音。扬声器解决不了这些问题;波形送到它之前,系统就得作出选择。

文本转语音(text-to-speech,TTS)把书面输入变成口语输出。任务包括确定语言内容、安排发音和时长、产生声学描述,再生成波形。这些职责可以由不同模块承担,也可以联合学习;画成流程图,并不表示所有系统都暴露相同接口。Flite的语言、词典和声音组件提供了一个具体的模块化例子。其中的“语言”组件不是ASR中给词序列打分的语言模型。Flite架构

如果应用只播放一组固定公告,一个实用的非AI基线是录好完整的、经过确认的句子,再按需要选取录音。这样能保留说话人的节奏,却不能朗读任意新文本。规则与词典前端扩展了覆盖范围,也让发音决策可以检查。学习式声学模型处理的是另一部分问题;加上它,不会自动修正错误的数字读法。

进入数学前,可先读Mel频谱和注意力。本篇集中讲前端与时长,不在这里重建整个波形合成器。

时长训练和舍入改变帧数;同样集中的注意力也可能按错误顺序前进。
时长训练和舍入改变帧数;同样集中的注意力也可能按错误顺序前进。

词、音素和帧,并不使用同一个时钟

下面是一种概念上的分工。输入文本记作aa,规范化后的词记作ww,发音单元记作pp,声学帧记作HH,波形采样点记作xx。它们的长度J,N,T,SJ,N,T,S不必相同:

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},

规范化回答的是“这段文本在当前应用中是什么意思”。同一串数字可能表示数量、日期或电话号码。发音阶段再通过词典,必要时加上缺词规则,把规范化后的词变成声音单元。固定版本的Flite源码检查token上下文和电话号码模式;把所有整数一律读成基数,会丢掉这种区别。本例只支持明确声明的小范围输入。固定前端源码

声学帧跨越一段时间,音素则描述语言中的声音内容。时长对齐连接这两者。设AA是非负的T×NT\times N注意力矩阵,每行和为1。把每个声学帧分配给它最关注的音素;本程序在同分时选择最小索引。公式中的音素编号从1开始,程序与路径例子的编号从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通过teacher注意力取得时长,并使用集中度分数FF选择注意力头。这些是推断出来的训练目标,不是人工认证的时长。倒序的one-hot路径也能和正确的正序路径一样得到focus为1。计数还会丢掉顺序:路径0、0、1、2、2、3与3、2、2、1、0、0产生相同的时长数组。FastSpeech §3.3

有了音素状态hih_i和时长估计did_i,长度调节器就按次数重复状态。本例明确采用下式的舍入约定,帧偏移从0开始:

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).

正数乘子α\alpha改变帧数。在声学帧步长固定时,乘子更大通常意味着说得更慢。舍入不可忽略:[2,2,3,1]乘.5,半数向上舍入得到[1,1,2,1],与Python默认的“同距取偶数”不同。次数为0会把某个音素从展开序列中删除;重复状态本身也不会产生发音动作或波形。长度调节

为了训练一个能看清每步计算的小模型,令XX包含nn行、每行dd个音素特征,ww是dd维系数向量。这里使用常数项、元音标记和停顿标记。给定整数合成目标时长DiD_i,最小化:

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.

其中λ\lambda是非负正则化强度。对平方残差使用链式法则,得到“两倍残差乘对应特征行”;累加各行,再对平方范数求导:

∇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.

这是以log1p时长为目标的线性回归,选择log1p是为了容纳零时长。FastSpeech描述的则是卷积时长预测器与log时长训练目标。本回归是教学替代物,不是那个预测器。仅在预测阶段采用的裁剪,把每个估计限制在0—32帧:

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

上面的梯度属于未裁剪的训练目标。若把裁剪后的输出当成也具有这个导数,描述的就会是另一个模型。训练每步成本为O(nd)O(nd),对齐计数为O(TN)O(TN);当状态维度为dd时,展开成本为O(d∑ici)O(d\sum_i c_i)。

为九个明确的发音单元训练时长

完整程序使用Python3.12和NumPy1.26.4。词典仅使用少量不带重音的发音标签,不是完整发音词典;read_sense负责提供同形词的读法。遇到未知词时,程序明确拒绝,而非悄悄编造发音。规范化能生成的一些词,例如“twenty”,并不在这个小词典中;两个阶段有各自的失败边界。

输入只允许短ASCII文本、一位或两位数字token和少数标点。小数、分组数字、字母数字混合token及未声明的语言形式都会失败。把标点映射为PAUSE也是本例的简化政策。模型在同一个九单元例子上拟合元音、辅音、停顿的4、2、6帧目标,不产生可朗读的波形。

"""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))

以.05步长更新150次后,目标从约1.800982降到.023390。默认舍入时长合计25帧,乘子.5时得到12帧。这是帧数,不是秒数;只有再乘以明确选定的声学帧步长,才有时间含义。学到的停顿约为4.83帧,而非精确6帧,因为目标含正则项,训练步数也有限。

再看两个对齐输出:它们的focus都为1,计数相同,但倒序路径有三次后退。missing_phone例子返回[0,1],直接暴露缩放和舍入造成的删除。最终录音即使听起来流畅,也不应该掩盖这两类问题。

波形很好听,也可能说错内容

本例把检查分为四层:先核对规范化词是否符合预期读法;再看发音与词典缺项;接着检查对齐顺序、覆盖和时长;如果加上波形阶段,最后再评价合成音频。单个时长损失不能替代这些不同观察。

扩展项目时,应声明一份留出的测试文本,包含歧义数字、生僻姓名、标点和长句。语言内容错误与时长误差分开记录。在明确硬件与输出长度的条件下,测量首段输出延迟和总合成时间;前端很快,不表示整套系统具备实时性能。听音评估也需要指定流程和听者。这个合成拟合例子没有进行这样的语音质量研究。

韵律还包括重音、语调和分句,不只是全局速度乘子。手写小词表与外部提供的同形词读法,有意把这些任务留在边界之外。更有表达能力的模型可以改变决策发生的位置,但仍需要检查最后实际说出了什么。

先核对读法,再相信声音

  1. 数字换了角色。应用把12当成两个编号数字。应该改变哪个阶段?重训时长回归能修复基数读法吗?

答案:规范化阶段应选择“one two”而非“twelve”。改变时长只会改变已选音素的节奏,不会替换底层词语。本例的digits模式把这个应用决策明确暴露出来。

  1. 手算长度调节。四个状态的时长为[2,2,3,1],乘子为.5,按程序约定舍入。结果有多少帧?

答案:缩放后[1,1,1.5,.5]变为[1,1,2,1],共5帧,状态索引依次为0、1、2、2、3。原总长8帧精确缩半是4帧,但这里是在每个音素上分别舍入。

  1. 一张很像正确答案的注意力图。每行都有一个1,但选中的音素索引倒着走。focus是多少?再检查什么能发现问题?

答案:focus为1,因为每行最大值都是1。检查连续选中位置,下降就暴露后退;还应统计覆盖,因为方向看似向前但不完整的路径也可能漏音素。

  1. 消失的音素。某个预测时长为.4,乘子为.5。应用可以直接宣布得到了正确的加速读法吗?

答案:缩放后的.2舍入成0,删除了这个音素。应用必须定义是拒绝这种设置、设定最小时长,还是允许特定删除。本例允许删除以展示边界;低回归损失无法替应用决定这些政策。

读模型名称,也要读模块边界

Flite的2001年论文支持语言、词典和声音模块的分工;固定源码给出使用上下文的前端实例。FastSpeech的2019年长度调节器则明确了另一种时长接口。本次核读的是相关架构和时长章节,没有核读所有基准。这里的原创程序没有借用上游实现或声音数据库。

继续学习时,可对比文本到声学帧的解码器与波形生成器:跨越模块边界的是哪种表示,时长在哪里决定,每种评估究竟能发现什么错误?

先判断,再看解释

注意力每行都是one-hot,但选中的音素索引倒着走,可以得出什么?

选择一个答案

学习目标

  • 区分文本规范化、发音、时长与波形生成。
  • 推导并训练有界对数时长回归模型。
  • 解释集中注意力为何不保证正确顺序。
  • 将语言错误与速度、音质分开评估。

先修与延伸

查看知识关联图 →

参考文献

  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

版本1 · 编写状态: 已完成记录中的技术复核

查看技术检查记录(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.

  • 核验基数/逐位规范化、外部同形词选择、小词典范围、log1p梯度和时长展开;focus为1的倒序路径计数相同但后退3次,25/12帧与删除0帧均实测。
  • 四张计算SVG绑定真实双语程序;本组14项数值/编码检查、24组语言/宽度及四字体检查通过,AI作者实际查看八张代表截图。冻结前检查普通正文AST;完整文章页面验收另记,不称人工同行审校。

核对的来源位置:

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。