Algorithm Search⌘K

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
Properties
deterministicexactnot in placeonline
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 fsf_s, an update period (5 ms), and for each update a fundamental frequency F0F_0 (0 for no voicing), a voicing amplitude AVA_V and KK formants (Fk,Bk)(F_k, B_k) 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 T=1/fsT = 1 / f_s, center frequency FF and bandwidth BB,

y[n]=A x[n]+B1 y[n−1]+C y[n−2],y[n] = A\, x[n] + B_1\, y[n-1] + C\, y[n-2],
C=−e−2πBT,B1=2e−πBTcos⁡(2πFT),A=1−B1−C.C = -e^{-2\pi B T}, \qquad B_1 = 2 e^{-\pi B T} \cos(2\pi F T), \qquad A = 1 - B_1 - C .

(Klatt calls the middle coefficient BB; it is B1B_1 here to keep it apart from the bandwidth.) Its transfer function is H(z)=A/(1−B1z−1−Cz−2)H(z) = A / (1 - B_1 z^{-1} - C z^{-2}). The poles are re±iθr e^{\pm i\theta} with r=e−πBTr = e^{-\pi B T} and θ=2πFT\theta = 2\pi F T, so the filter rings at FF and its envelope decays at a rate set by BB. The choice of AA makes the gain at 0 Hz exactly 1. An antiresonator, for the zeros of nasals, uses A′=1/AA' = 1/A, B1′=−B1/AB_1' = -B_1/A, C′=−C/AC' = -C/A in y[n]=A′x[n]+B1′x[n−1]+C′x[n−2]y[n] = A' x[n] + B_1' x[n-1] + C' x[n-2], 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.

  1. FORMANT-SYNTHESIS(frames of (F0, AV, (F_1, B_1) .. (F_K, B_K)), fs)
  2. 1for each parameter frame do
  3. 2compute (A_k, B1_k, C_k) for every formant k
  4. 3for each of the fs * 0.005 samples of the frame: emit a pulse of size AV when the pitch phase wraps, else 0
  5. 4v <- the pulse through a low-pass resonator at 0 Hz (the glottal source)
  6. 5for k <- 1 to K do v <- A_k v + B1_k y_k[n-1] + C_k y_k[n-2]
  7. 6output v - v_previous (the radiation at the lips)

The states yk[n−1]y_k[n-1] and yk[n−2]y_k[n-2] carry over from frame to frame, so a change of a formant does not reset the filter and does not click.

Example

Take fs=10000f_s = 10000 Hz, F=500F = 500 Hz and B=60B = 60 Hz. Then r=e−π⋅0.006=0.98133r = e^{-\pi \cdot 0.006} = 0.98133 and θ=0.31416\theta = 0.31416 rad, and

C=−0.9630027,B1=1.8665948,A=1−1.8665948+0.9630027=0.0964078.C = -0.9630027, \qquad B_1 = 1.8665948, \qquad A = 1 - 1.8665948 + 0.9630027 = 0.0964078 .

The impulse response starts 0.096408, 0.179954, 0.243061, 0.280400, 0.289324, a sinusoid of 500 Hz under the envelope Arn/sin⁡θA r^n / \sin\theta. 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 FF, and the gain falls by 3 dB at 468.1 and 528.4 Hz, a width of 60.25 Hz, close to BB. The peak gain is close to F/B=8.33F / B = 8.33.

A vowel like /a/ with F0=100F_0 = 100 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 B>0B > 0, since r<1r < 1; the impulse response is h[n]=Arnsin⁡((n+1)θ)/sin⁡θh[n] = A r^n \sin((n+1)\theta) / \sin\theta; the peak of ∣H∣|H| is where cos⁡ω=(1+r2)cos⁡θ/(2r)\cos\omega = (1 + r^2) \cos\theta / (2r), when this is in [−1,1][-1, 1]; the antiresonator is the exact inverse; and a cascade has the product of the responses. That the half-power width is close to BB is an approximation for B≪fsB \ll f_s, 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, T=1/fsT = 1/f_s, FF is the center frequency, B>0B > 0 the bandwidth, r=e−πBTr = e^{-\pi B T} and θ=2πFT\theta = 2\pi F T with 0≤θ≤π0 \le \theta \le \pi, and

C=−e−2πBT=−r2,B1=2e−πBTcos⁡(2πFT)=2rcos⁡θ,A=1−B1−C.C = -e^{-2\pi B T} = -r^2, \qquad B_1 = 2 e^{-\pi B T} \cos(2\pi F T) = 2 r \cos\theta, \qquad A = 1 - B_1 - C .

The resonator is y[n]=Ax[n]+B1y[n−1]+Cy[n−2]y[n] = A x[n] + B_1 y[n-1] + C y[n-2], with transfer function H(z)=A/(1−B1z−1−Cz−2)H(z) = A / (1 - B_1 z^{-1} - C z^{-2}).

Lemma 1 (the poles)

1−B1z−1−Cz−2=(1−reiθz−1)(1−re−iθz−1)1 - B_1 z^{-1} - C z^{-2} = (1 - r e^{i\theta} z^{-1})(1 - r e^{-i\theta} z^{-1}). So the poles are re±iθr e^{\pm i\theta}, and since 0<r<10 < r < 1 for B>0B > 0, the filter is stable.

Proof. Expand the right side: 1−r(eiθ+e−iθ)z−1+r2z−2=1−2rcos⁡θ z−1+r2z−21 - r(e^{i\theta} + e^{-i\theta}) z^{-1} + r^2 z^{-2} = 1 - 2r\cos\theta\, z^{-1} + r^2 z^{-2}, which is 1−B1z−1−Cz−21 - B_1 z^{-1} - C z^{-2}. A causal rational filter is stable if and only if its poles are inside the unit circle, and ∣re±iθ∣=r=e−πBT<1|r e^{\pm i\theta}| = r = e^{-\pi B T} < 1. □\square

Lemma 2 (unit gain at 0 Hz)

H(1)=1H(1) = 1. Hence a constant input x[n]=cx[n] = c gives an output that tends to cc.

Proof. H(1)=A/(1−B1−C)=A/A=1H(1) = A / (1 - B_1 - C) = A / A = 1, and A=(1−reiθ)(1−re−iθ)=∣1−reiθ∣2>0A = (1 - r e^{i\theta})(1 - r e^{-i\theta}) = |1 - r e^{i\theta}|^2 > 0 by Lemma 1 at z=1z = 1, so the division is defined. For a stable filter, the response to a step of size cc tends to cH(1)c H(1). □\square

Lemma 3 (the impulse response)

For 0<θ<π0 < \theta < \pi, the impulse response is h[n]=Arnsin⁡((n+1)θ)/sin⁡θh[n] = A r^n \sin((n+1)\theta) / \sin\theta for n≥0n \ge 0.

Proof. Let g[n]=rnsin⁡((n+1)θ)/sin⁡θg[n] = r^n \sin((n+1)\theta) / \sin\theta. Then g[0]=1g[0] = 1 and g[1]=rsin⁡2θ/sin⁡θ=2rcos⁡θ=B1g[1] = r \sin 2\theta / \sin\theta = 2r\cos\theta = B_1. For n≥2n \ge 2, the identity sin⁡((n+1)θ)=2cos⁡θsin⁡(nθ)−sin⁡((n−1)θ)\sin((n+1)\theta) = 2\cos\theta \sin(n\theta) - \sin((n-1)\theta) gives

g[n]=2rcos⁡θ⋅rn−1sin⁡(nθ)sin⁡θ−r2⋅rn−2sin⁡((n−1)θ)sin⁡θ=B1g[n−1]+Cg[n−2].g[n] = 2r\cos\theta \cdot r^{n-1} \frac{\sin(n\theta)}{\sin\theta} - r^2 \cdot r^{n-2} \frac{\sin((n-1)\theta)}{\sin\theta} = B_1 g[n-1] + C g[n-2].

The impulse response satisfies h[0]=Ah[0] = A, h[1]=B1h[0]=AB1h[1] = B_1 h[0] = A B_1, and h[n]=B1h[n−1]+Ch[n−2]h[n] = B_1 h[n-1] + C h[n-2] for n≥2n \ge 2. So hh and AgA g satisfy the same recursion with the same first two values, and they are equal by induction. □\square

Lemma 4 (the peak)

Let c∗=(1+r2)cos⁡θ/(2r)c^* = (1 + r^2)\cos\theta / (2r). On 0≤ω≤π0 \le \omega \le \pi, ∣H(eiω)∣|H(e^{i\omega})| has its maximum at ω∗=arccos⁡c∗\omega^* = \arccos c^* if −1≤c∗≤1-1 \le c^* \le 1, and at ω=0\omega = 0 if c∗>1c^* > 1.

Proof. By Lemma 1, ∣H(eiω)∣−2=A−2∣eiω−reiθ∣2∣eiω−re−iθ∣2|H(e^{i\omega})|^{-2} = A^{-2} |e^{i\omega} - r e^{i\theta}|^2 |e^{i\omega} - r e^{-i\theta}|^2. Expand each factor: ∣eiω−re±iθ∣2=1+r2−2rcos⁡(ω∓θ)|e^{i\omega} - r e^{\pm i\theta}|^2 = 1 + r^2 - 2r\cos(\omega \mp \theta). Their product, with p=1+r2p = 1 + r^2 and u=cos⁡ωu = \cos\omega, is

(p−2rcos⁡(ω−θ))(p−2rcos⁡(ω+θ))=p2−2rp⋅2cos⁡ωcos⁡θ+4r2cos⁡(ω−θ)cos⁡(ω+θ).(p - 2r\cos(\omega - \theta))(p - 2r\cos(\omega + \theta)) = p^2 - 2rp \cdot 2\cos\omega\cos\theta + 4r^2 \cos(\omega - \theta)\cos(\omega + \theta).

With cos⁡(ω−θ)cos⁡(ω+θ)=cos⁡2ω−sin⁡2θ=u2−sin⁡2θ\cos(\omega - \theta)\cos(\omega + \theta) = \cos^2\omega - \sin^2\theta = u^2 - \sin^2\theta, this is Q(u)=4r2u2−4rpcos⁡θ u+p2−4r2sin⁡2θQ(u) = 4r^2 u^2 - 4rp\cos\theta\, u + p^2 - 4r^2\sin^2\theta, a quadratic in uu with positive leading coefficient. Its minimum over the reals is at u=pcos⁡θ/(2r)=c∗u = p\cos\theta / (2r) = c^*. The gain is largest where QQ is least. If c∗∈[−1,1]c^* \in [-1, 1], the least value on u∈[−1,1]u \in [-1, 1] is at u=c∗u = c^*, that is ω=arccos⁡c∗\omega = \arccos c^*. If c∗>1c^* > 1, QQ is decreasing on [−1,1][-1, 1], so the least value is at u=1u = 1, ω=0\omega = 0. □\square

Since (1+r2)/(2r)≥1(1 + r^2)/(2r) \ge 1, with equality only at r=1r = 1, we have ∣c∗∣≥∣cos⁡θ∣|c^*| \ge |\cos\theta|, so the peak is below FF when θ<π/2\theta < \pi/2 and moves further down as BB grows. In the example of the page, F=500F = 500, B=60B = 60 and fs=10000f_s = 10000 give ω∗fs/2π=499.13\omega^* f_s / 2\pi = 499.13 Hz.

Lemma 5 (the antiresonator is the inverse)

With A′=1/AA' = 1/A, B1′=−B1/AB_1' = -B_1/A and C′=−C/AC' = -C/A, the filter y[n]=A′x[n]+B1′x[n−1]+C′x[n−2]y[n] = A' x[n] + B_1' x[n-1] + C' x[n-2] has H′(z)=(1−B1z−1−Cz−2)/A=1/H(z)H'(z) = (1 - B_1 z^{-1} - C z^{-2}) / A = 1 / H(z). So a resonator followed by the antiresonator with the same FF and BB returns the input exactly, from zero states.

Proof. H′(z)=A′+B1′z−1+C′z−2=(1−B1z−1−Cz−2)/AH'(z) = A' + B_1' z^{-1} + C' z^{-2} = (1 - B_1 z^{-1} - C z^{-2}) / A, and H(z)H′(z)=1H(z) H'(z) = 1. Both filters are causal and start from zero states, so the output of the pair is the input convolved with the impulse response of HH′=1H H' = 1, which is the input. □\square

Lemma 6 (the cascade)

If KK resonators with fixed coefficients are in series, the transfer function of the chain is ∏kHk(z)\prod_k H_k(z), 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 z=1z = 1, each factor is 1 by Lemma 2. □\square

The synthesis loop

When the coefficients change at a frame boundary, the states y[n−1]y[n-1] and y[n−2]y[n-2] 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 v[n]−v[n−1]v[n] - v[n-1] has the response 1−e−iω1 - e^{-i\omega}, 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 BB when BTB T is small: near the peak, ∣eiω−reiθ∣2≈(1−r)2+(ω−θ)2|e^{i\omega} - r e^{i\theta}|^2 \approx (1 - r)^2 + (\omega - \theta)^2, which doubles at ∣ω−θ∣=1−r≈πBT|\omega - \theta| = 1 - r \approx \pi B T, a total width of 2πBT2\pi B T in radians, that is BB 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 O(NK)O(N K) for NN samples and KK resonators, plus O(PK)O(P K) for the coefficients of PP frames, each with one exponential and one cosine per resonator. The memory is two state values per resonator, O(K)O(K). With K=5K = 5 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 TT. Formants above fs/2f_s / 2 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 F/BF / B, so a narrow, high formant can overflow a fixed-point output. Scale the source.
  • A bandwidth of zero. Then r=1r = 1 and the resonator never decays. Keep B>0B > 0.
  • The peak is not at FF. For wide bandwidths at low frequencies the peak moves below FF, and if (1+r2)cos⁡θ/(2r)>1(1 + r^2)\cos\theta / (2r) > 1 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.

formant_synthesis.pyI0RawGitHub
# 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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example