Algorithmcore
Formant synthesis
Also called Klatt synthesizer.
Make speech by passing a source signal through resonators set to formant frequencies and bandwidths, controlled by rules over time.
- Time
- O(N K + P K) worst
- Space
- O(K) extra
- Where
- K = the number of resonators; N = the number of output samples; P = the number of parameter frames
- Model
- Real RAM
- Properties
- deterministicexactnot in placeonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Dennis H. Klatt, 1980
Formant synthesis makes speech from a few slowly changing numbers: a pitch, a source amplitude and the frequencies and bandwidths of the formants, the resonances of the vocal tract. A source of pulses or noise goes through a chain of second-order digital resonators, one per formant, as in the source-filter model. It is the inverse of formant estimation, which reads the formants from speech, and the oldest method of text-to-speech, where rules set the parameters over time; later methods such as unit selection and PSOLA join recorded speech instead.
In plain words
When you say a vowel, your vocal folds make a buzz of short pulses, and your mouth and throat make some frequencies of that buzz louder than others. Those loud regions are the formants, and they tell the listener which vowel it is. A formant synthesizer copies this with arithmetic. It makes a train of pulses at the pitch you want. It sends them through a few simple filters, each of which rings at one frequency, like a bell, and dies away at a set speed. Every few milliseconds the program changes the pitch and the ring frequencies, and the vowel and pitch change with them. For sounds like "s", it uses noise instead of pulses.
The problem
Given a sample rate , an update period (5 ms), and for each update a fundamental frequency (0 for no voicing), a voicing amplitude and formants in Hz, produce the samples of the speech wave. The text-to-speech problem adds the rules that turn phonemes into these parameter tracks; this page covers the signal part.
The algorithm
The building block is the digital resonator of Klatt's equations 1 and 2. With the sample period , center frequency and bandwidth ,
(Klatt calls the middle coefficient ; it is here to keep it apart from the bandwidth.) Its transfer function is . The poles are with and , so the filter rings at and its envelope decays at a rate set by . The choice of makes the gain at 0 Hz exactly 1. An antiresonator, for the zeros of nasals, uses , , in , which is the inverse of the resonator (equations 4 and 5).
In the cascade form for vowels the resonators are in series, so their responses multiply and the relative formant levels come out right without separate gains. A parallel branch, with one gain per formant, is better for fricatives and is not in the code below.
FORMANT-SYNTHESIS(frames of (F0, AV, (F_1, B_1) .. (F_K, B_K)), fs)- 1
for each parameter frame do - 2
compute (A_k, B1_k, C_k) for every formant k - 3
for each of the fs * 0.005 samples of the frame: emit a pulse of size AV when the pitch phase wraps, else 0 - 4
v <- the pulse through a low-pass resonator at 0 Hz (the glottal source) - 5
for k <- 1 to K do v <- A_k v + B1_k y_k[n-1] + C_k y_k[n-2] - 6
output v - v_previous (the radiation at the lips)
The states and carry over from frame to frame, so a change of a formant does not reset the filter and does not click.
Example
Take Hz, Hz and Hz. Then and rad, and
The impulse response starts 0.096408, 0.179954, 0.243061, 0.280400, 0.289324, a sinusoid of 500 Hz under the envelope . The gain at some frequencies:
| frequency (Hz) | 0 | 250 | 470 | 500 | 530 | 1000 | 2000 | 5000 |
|---|---|---|---|---|---|---|---|---|
| gain | 1.000 | 1.330 | 6.139 | 8.429 | 5.793 | 0.345 | 0.077 | 0.025 |
| dB | 0.0 | 2.5 | 15.8 | 18.5 | 15.3 | -9.2 | -22.3 | -32.0 |
The peak is at 499.13 Hz, slightly below , and the gain falls by 3 dB at 468.1 and 528.4 Hz, a width of 60.25 Hz, close to . The peak gain is close to .
A vowel like /a/ with Hz, formants (700, 130), (1220, 70) and (2600, 160) and a glottal low-pass with a bandwidth of 100 Hz gives a wave that repeats every 100 samples once the start has decayed. Its harmonics at 700 and 1200 Hz are more than three times as strong as those at 1000 and 1900 Hz, between the formants.
Correctness
The output is a fixed linear recursion of the parameters, so the claims to prove are the properties of the resonator. These are theorems, proved in proofs/correctness.md: the gain at 0 Hz is 1; the filter is stable for every , since ; the impulse response is ; the peak of is where , when this is in ; the antiresonator is the exact inverse; and a cascade has the product of the responses. That the half-power width is close to is an approximation for , checked here as a measurement.
Whether the output sounds like the intended speech depends on the rules and the parameters, which no theorem covers.
Proof: Correctness of the digital formant resonatorfull
Formant synthesis is a fixed linear recursion, so its correctness is the set of properties of the resonator that the method relies on. Throughout, , is the center frequency, the bandwidth, and with , and
The resonator is , with transfer function .
Lemma 1 (the poles)
. So the poles are , and since for , the filter is stable.
Proof. Expand the right side: , which is . A causal rational filter is stable if and only if its poles are inside the unit circle, and .
Lemma 2 (unit gain at 0 Hz)
. Hence a constant input gives an output that tends to .
Proof. , and by Lemma 1 at , so the division is defined. For a stable filter, the response to a step of size tends to .
Lemma 3 (the impulse response)
For , the impulse response is for .
Proof. Let . Then and . For , the identity gives
The impulse response satisfies , , and for . So and satisfy the same recursion with the same first two values, and they are equal by induction.
Lemma 4 (the peak)
Let . On , has its maximum at if , and at if .
Proof. By Lemma 1, . Expand each factor: . Their product, with and , is
With , this is , a quadratic in with positive leading coefficient. Its minimum over the reals is at . The gain is largest where is least. If , the least value on is at , that is . If , is decreasing on , so the least value is at , .
Since , with equality only at , we have , so the peak is below when and moves further down as grows. In the example of the page, , and give Hz.
Lemma 5 (the antiresonator is the inverse)
With , and , the filter has . So a resonator followed by the antiresonator with the same and returns the input exactly, from zero states.
Proof. , and . Both filters are causal and start from zero states, so the output of the pair is the input convolved with the impulse response of , which is the input.
Lemma 6 (the cascade)
If resonators with fixed coefficients are in series, the transfer function of the chain is , and its gain at 0 Hz is 1.
Proof. Each section is a linear time-invariant filter, and the transfer function of a series of such filters is the product of theirs, since the z-transform turns convolution into multiplication. At , each factor is 1 by Lemma 2.
The synthesis loop
When the coefficients change at a frame boundary, the states and keep their values, so the output is continuous in the sense that the new recursion starts from the old state; the system is then linear but not time-invariant, and Lemmas 3 and 4 hold only inside each frame. The radiation step has the response , which is 0 at 0 Hz and rises by 6 dB per octave at low frequencies. The whole chain therefore passes no DC, by design.
The half-power width of a single resonator is close to when is small: near the peak, , which doubles at , a total width of in radians, that is in Hz. This is a first-order approximation, not an identity, and the tests check it only to 3 percent.
Complexity
Each output sample costs one source step and one resonator step per formant, three multiplications each, so the time is for samples and resonators, plus for the coefficients of frames, each with one exponential and one cosine per resonator. The memory is two state values per resonator, . With formants at 10 kHz this is about 150000 multiplications per second.
Properties
- Few parameters. About 10 to 40 numbers every 5 ms describe the speech, which is why formant synthesis was used for very small systems and for speech research.
- Full control. Each acoustic property can be changed alone, which makes it the tool for perception experiments.
- Intelligible but not natural. Rule-driven formant synthesis can be highly intelligible but sounds buzzy and machine-like, because the simple source and the rules miss the fine detail of real speech; this is a judgment of listeners, measured with tests such as the mean opinion score.
- Online. Each sample depends only on the past, so the output can stream.
Variants and improvements
- Parallel branch. Each formant has its own gain and the outputs add. This gives control of the levels for fricatives and plosives, at the cost of setting more gains.
- Better sources. A glottal pulse model with an open and a closed phase, instead of filtered impulses, gives a more natural voice; later versions of the design added such sources.
- Noise source. Gaussian or uniform noise through the same resonators gives aspiration and frication.
- Rules. Text-to-speech systems of the 1970s and 1980s, such as MITalk and its commercial descendant DECtalk, drove formant synthesizers with rules for each phoneme and its neighbors.
- Articulatory synthesis. Instead of formants, simulate the shape of the vocal tract; the formants then follow from the shape.
When to use it
Use formant synthesis for speech perception experiments, where each cue must be set exactly, for teaching acoustics, and for systems with very little memory. For natural-sounding text-to-speech, neural methods such as WaveNet and HiFi-GAN have replaced it.
Pitfalls
- Coefficients from the wrong rate. The coefficients depend on . Formants above fold back, so at 10 kHz the formants must stay below 5 kHz.
- Resetting the state. Making a new filter at each frame, instead of changing the coefficients of the running one, gives clicks at the frame edges.
- Gain at the formant. The gain at the peak is about , so a narrow, high formant can overflow a fixed-point output. Scale the source.
- A bandwidth of zero. Then and the resonator never decays. Keep .
- The peak is not at . For wide bandwidths at low frequencies the peak moves below , and if there is no peak above 0 Hz at all.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/formant-synthesis/. The authors are listed in prov/D7ZPSZ.jsonl.
"""Cascade formant synthesis with the digital resonators of Klatt (1980).
A resonator with center frequency F and bandwidth BW at the sample period T is
y[n] = A x[n] + B y[n - 1] + C y[n - 2],
C = -exp(-2 pi BW T), B = 2 exp(-pi BW T) cos(2 pi F T), A = 1 - B - C,
so its gain at 0 Hz is A / (1 - B - C) = 1. An antiresonator inverts it:
y[n] = A' x[n] + B' x[n - 1] + C' x[n - 2], A' = 1 / A, B' = -B / A, C' = -C / A.
The synthesizer reads one frame of parameters every update period (5 ms in
Klatt's design): F0, the voicing amplitude AV, and the formants (F_k, BW_k).
The source is a train of unit impulses at F0 through a low-pass resonator at
0 Hz. The formant resonators are in cascade, and a first difference models the
radiation at the lips. Filter states carry over from frame to frame.
"""
import cmath
import math
from typing import List, Sequence, Tuple
Coeffs = Tuple[float, float, float]
def resonator_coeffs(f: float, bw: float, fs: float) -> Coeffs:
"""(A, B, C) of the resonator with center f and bandwidth bw in Hz at the sample rate fs."""
t = 1.0 / fs
c = -math.exp(-2.0 * math.pi * bw * t)
b = 2.0 * math.exp(-math.pi * bw * t) * math.cos(2.0 * math.pi * f * t)
return 1.0 - b - c, b, c
def antiresonator_coeffs(f: float, bw: float, fs: float) -> Coeffs:
"""(A', B', C') of the antiresonator, the inverse of the resonator with the same f and bw."""
a, b, c = resonator_coeffs(f, bw, fs)
return 1.0 / a, -b / a, -c / a
class Resonator:
"""y[n] = A x[n] + B y[n - 1] + C y[n - 2]. The coefficients can change between samples; the state stays."""
def __init__(self) -> None:
self.y1 = 0.0
self.y2 = 0.0
def step(self, x: float, k: Coeffs) -> float:
y = k[0] * x + k[1] * self.y1 + k[2] * self.y2
self.y2, self.y1 = self.y1, y
return y
class Antiresonator:
"""y[n] = A' x[n] + B' x[n - 1] + C' x[n - 2]."""
def __init__(self) -> None:
self.x1 = 0.0
self.x2 = 0.0
def step(self, x: float, k: Coeffs) -> float:
y = k[0] * x + k[1] * self.x1 + k[2] * self.x2
self.x2, self.x1 = self.x1, x
return y
def filter_signal(x: Sequence[float], k: Coeffs, anti: bool = False) -> List[float]:
"""Run a fixed resonator (or antiresonator) over x from a zero state."""
r = Antiresonator() if anti else Resonator()
return [r.step(v, k) for v in x]
def response(k: Coeffs, f: float, fs: float, anti: bool = False) -> complex:
"""The frequency response at f Hz: A / (1 - B z^-1 - C z^-2), or A' + B' z^-1 + C' z^-2, with z = exp(i 2 pi f / fs)."""
zi = cmath.exp(-2j * math.pi * f / fs)
if anti:
return k[0] + k[1] * zi + k[2] * zi * zi
return k[0] / (1.0 - k[1] * zi - k[2] * zi * zi)
def synthesize(
frames: Sequence[Tuple[float, float, Sequence[Tuple[float, float]]]],
fs: float,
update: float = 0.005,
glottal_bw: float = 100.0,
) -> List[float]:
"""Cascade synthesis. frames[i] = (F0 in Hz, AV, [(F_1, BW_1), ..., (F_K, BW_K)]); F0 = 0 gives silence.
Each frame lasts update seconds. Returns the samples.
"""
per_frame = round(update * fs)
k_max = max(len(fr[2]) for fr in frames) if frames else 0
formants = [Resonator() for _ in range(k_max)]
glottis = Resonator()
glottal = resonator_coeffs(0.0, glottal_bw, fs)
last = 0.0 # for the radiation difference
phase = 1.0 # a pulse at the first voiced sample
out: List[float] = []
for f0, av, fmts in frames: # @line L1
coeffs = [resonator_coeffs(f, bw, fs) for f, bw in fmts] # @line L2
for _ in range(per_frame):
pulse = 0.0
if f0 > 0:
if phase >= 1.0: # @line L3
pulse = av
phase -= 1.0
phase += f0 / fs
v = glottis.step(pulse, glottal) # @line L4
for res, k in zip(formants, coeffs):
v = res.step(v, k) # @line L5
out.append(v - last) # @line L6
last = v
return out
test_formant_synthesis.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/formant-synthesis/. The authors are listed in prov/D7ZPSZ.jsonl.
import math
import random
from formant_synthesis import (
antiresonator_coeffs,
filter_signal,
resonator_coeffs,
response,
synthesize,
)
FS = 10000
def test_unit_gain_at_zero_hertz():
for f, bw in ((500, 60), (1500, 90), (3000, 250), (0, 100)):
k = resonator_coeffs(f, bw, FS)
assert abs(sum(filter_signal([1.0] * 3000, k)[-1:]) - 1.0) < 1e-6 # a step settles at gain 1
assert abs(response(k, 0, FS) - 1.0) < 1e-12
assert abs(response(antiresonator_coeffs(f, bw, FS), 0, FS) - 1.0) < 1e-12
def test_coefficients_of_the_example():
a, b, c = resonator_coeffs(500, 60, FS)
assert abs(a - 0.0964078) < 1e-7
assert abs(b - 1.8665948) < 1e-7
assert abs(c + 0.9630027) < 1e-7
def test_impulse_response_is_a_damped_sinusoid():
f, bw = 500, 60
k = resonator_coeffs(f, bw, FS)
r = math.exp(-math.pi * bw / FS)
theta = 2 * math.pi * f / FS
h = filter_signal([1.0] + [0.0] * 199, k)
for n, v in enumerate(h):
assert abs(v - k[0] * r**n * math.sin((n + 1) * theta) / math.sin(theta)) < 1e-12
def test_peak_is_where_the_closed_form_says_and_near_the_center():
for f, bw in ((500, 60), (1200, 80), (2500, 200), (300, 150)):
k = resonator_coeffs(f, bw, FS)
r = math.exp(-math.pi * bw / FS)
theta = 2 * math.pi * f / FS
want = math.acos((1 + r * r) * math.cos(theta) / (2 * r)) * FS / (2 * math.pi)
grid = [f - 200 + i * 0.01 for i in range(40001)]
got = max(grid, key=lambda g: abs(response(k, g, FS)))
assert abs(got - want) < 0.02
assert abs(got - f) < bw # the peak is close to the center, closer when bw is small
def test_half_power_bandwidth_is_close_to_bw_for_narrow_resonances():
for f, bw in ((500, 60), (1500, 90), (2500, 120)):
k = resonator_coeffs(f, bw, FS)
top = abs(response(k, f, FS))
grid = [f - 300 + i * 0.05 for i in range(12001)]
inside = [g for g in grid if abs(response(k, g, FS)) >= top / math.sqrt(2)]
assert abs((inside[-1] - inside[0]) - bw) < 0.03 * bw # a measurement, not a theorem
def test_antiresonator_undoes_the_resonator():
rng = random.Random(1)
x = [rng.uniform(-1, 1) for _ in range(500)]
y = filter_signal(filter_signal(x, resonator_coeffs(800, 100, FS)), antiresonator_coeffs(800, 100, FS), anti=True)
assert max(abs(a - b) for a, b in zip(x, y)) < 1e-9
def test_cascade_is_the_product_of_the_sections():
fmts = [(700, 130), (1220, 70), (2600, 160)]
ks = [resonator_coeffs(f, bw, FS) for f, bw in fmts]
h = [1.0] + [0.0] * 2047
for k in ks:
h = filter_signal(h, k)
for f in (100, 700, 1220, 2000, 2600, 4000):
z = [complex(math.cos(2 * math.pi * f * n / FS), -math.sin(2 * math.pi * f * n / FS)) for n in range(2048)]
dtft = sum(v * w for v, w in zip(h, z))
prod = 1.0
for k in ks:
prod *= response(k, f, FS)
assert abs(dtft - prod) < 1e-6
def test_synthesized_vowel_has_the_pitch_period_and_formant_peaks():
frames = [(100, 1.0, [(700, 130), (1220, 70), (2600, 160)])] * 40 # 0.2 s of a vowel like /a/
x = synthesize(frames, FS)
assert len(x) == 2000
# the output repeats every 100 samples once the start has decayed
assert max(abs(x[n] - x[n + 100]) for n in range(1500, 1900)) < 1e-6
# the harmonics near the formants are stronger than those between them
seg = x[1000:2000]
def harmonic(f):
return abs(sum(v * complex(math.cos(2 * math.pi * f * n / FS), -math.sin(2 * math.pi * f * n / FS)) for n, v in enumerate(seg)))
assert harmonic(700) > 3 * harmonic(1000)
assert harmonic(1200) > 3 * harmonic(1900)
def test_silence_when_f0_is_zero():
assert synthesize([(0, 1.0, [(500, 60)])] * 3, FS) == [0.0] * 150
History
Electrical formant synthesizers appeared in the 1950s, among them Walter Lawrence's Parametric Artificial Talker (PAT) in England and Gunnar Fant's OVE in Sweden. John Holmes and others built rule systems for them in the 1960s. Dennis Klatt at MIT published a software design in 1980 with both a cascade and a parallel branch, sampled at 10 kHz and updated every 5 ms, and printed its FORTRAN code. Klatt's work led to the MITalk system and to DECtalk, which gave a voice to many users of speech aids. Since the 1990s, concatenative and then neural methods have replaced formant synthesis in products.
References
- Dennis H. Klatt, Software for a cascade/parallel formant synthesizer, Journal of the Acoustical Society of America 67(3), 1980, 971 to 995, equations 1 to 5 (the digital resonator, its transfer function and the antiresonator), the description of the cascade and parallel branches, and Appendix B (the program listing)
- Lawrence R. Rabiner and Ronald W. Schafer, Digital Processing of Speech Signals, Prentice-Hall, 1978, Chapter 3 (digital models of the speech signal, the vocal tract as a cascade of resonators)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag D7ZPSZ Edit this page History Report an error Markdown