Sound Synthesis with Fourier Series — Harmonics and Waveform Construction
Go deeper on this topic
Creative Coding
Mathematical simulations, nature visualization, and generative art in the browser
Article 10 of 12 in this series.
Next reads
Ant Colony Simulation — Emergent Swarm Intelligence Through Pheromones
Implementing pheromone-based pathfinding with an agent-based model to reproduce ant swarm intelligence in the browser. Explores how evaporation and diffusion parameters affect emergent patterns.
60fps Particles with Canvas API — Smooth Animation Design for 200+ Particles
Design techniques for running 200+ particles at 60fps using Canvas API with requestAnimationFrame, fixed timestep, DPI scaling, and spatial partitioning.
The World of Cellular Automata — From Game of Life to Wave Function Collapse
Design patterns for rule-based cellular automata and grid optimization with Uint8Array, explored through implementations of Game of Life, WaveFunctionCollapse, and SandFall.
Use the topic hub as a map, then continue to the next article in the series. New here? Start at the home hub →
Why Fourier Series
"Every periodic function can be expressed as a superposition of sines and cosines." When Joseph Fourier proposed this in 1807, mathematicians of the era were skeptical. But it was correct, and it became the foundation of modern signal processing, acoustics, and image compression.
What makes Fourier series fascinating is how abstract mathematics connects directly to the bodily sensation of "timbre." Why a square wave sounds sharp, why a triangle wave sounds soft — it's all explained by the harmonic structure, i.e., the Fourier coefficients.
The FourierSeries component (402 lines) uses the Canvas API to perform real-time Fourier synthesis of three waveforms and visualize them with epicycles (chains of rotating circles). Moving the number of terms from 1 to 30 reveals the process of sine wave superposition "converging" toward the target waveform.
Three Waveforms and Their Series Expansions
Square Wave
The Fourier series expansion of a square wave contains only odd harmonics:
f(x) = Σ [4/(π·n) · sin(2πnfx)], n = 1, 3, 5, ... (odd only)In the implementation, k is the index and n = 2k + 1 generates odd numbers:
case 'square': {
n = 2 * k + 1
amplitude = 4 / (Math.PI * n)
break
}The amplitude decays as 1/n, so higher harmonics remain relatively strong. This produces the square wave's "sharp" and "hollow" timbre. The clarinet's sound is said to resemble a square wave because the physics of the instrument cause odd harmonics to dominate over even ones.
With just 1 term, it's a plain sine wave. Adding the 3rd harmonic (n=3) makes the shoulders slightly angular, and as 5th, 7th, and higher harmonics are added, the shape gradually approaches a rectangle. However, no matter how many terms are added, "whiskers" remain near the discontinuities. This is the Gibbs phenomenon.
Sawtooth Wave
A sawtooth wave contains all harmonics — both even and odd:
f(x) = Σ [(2/π) · (-1)^(n+1) / n · sin(2πnfx)], n = 1, 2, 3, ...case 'sawtooth': {
n = k + 1
amplitude = (2 / Math.PI) * ((-1) ** (n + 1) / n)
break
}(-1)^(n+1) represents alternating signs: positive at n=1, negative at n=2, positive at n=3, and so on. Containing all harmonics means the harmonic content is the "richest."
The bowing sound of string instruments (drawing a bow across a string) resembles a sawtooth wave because the string is pulled linearly by the bow and then snaps back rapidly — this motion pattern produces a sawtooth-shaped waveform. Looking at a slowly bowed open violin string on an oscilloscope reveals something quite close to a sawtooth wave.
Triangle Wave
A triangle wave, like a square wave, contains only odd harmonics, but the amplitude decays as 1/n²:
f(x) = Σ [(8/π²) · (-1)^k / (2k+1)² · sin(2π(2k+1)fx)], k = 0, 1, 2, ...case 'triangle': {
n = 2 * k + 1
amplitude = ((8 / (Math.PI * Math.PI)) * (-1) ** k) / (n * n)
break
}The 1/n² decay is overwhelmingly faster than 1/n. The 3rd harmonic's amplitude is 1/9 of the fundamental, the 5th is 1/25, the 7th is 1/49 — decreasing rapidly. Very little high-frequency content remains.
This is why the timbre resembles a flute's soft sound. The flute is known among wind instruments for having few harmonics (close to a pure tone). The "round" timbre of a triangle wave is nothing but the auditory expression of extremely weak higher harmonics.
Visualization with Epicycles
The FourierSeries component screen is divided left and right. The left 40% is the epicycle area, and the right 60% is the waveform drawing area:
const EPICYCLE_SPLIT = 0.4
const WAVEFORM_GAP = 20
const TRAIL_LENGTH = 400An epicycle is a drawing technique where "a rotating circle is placed on top of another rotating circle." Each Fourier term corresponds to one circle:
for (let i = 0; i < coeffs.length; i++) {
const { n, amplitude, phase } = coeffs[i]
const r = Math.abs(amplitude) * scale
const angle = n * t + phase
// Draw circle
ctx.beginPath()
ctx.arc(x, y, r, 0, Math.PI * 2)
ctx.stroke()
// Next circle's center = point on current circle's edge
x += Math.cos(angle) * Math.abs(amplitude) * scale
y -= Math.sin(angle) * Math.abs(amplitude) * scale
}radius = |amplitude_n| × scale for scaling. The fundamental (n=1) circle is largest, with higher harmonic circles progressively smaller. For triangle waves, the 1/n² decay makes circles beyond the 3rd barely visible as dots. For square waves, 1/n decay keeps higher-order circles at a reasonable size.
The y-coordinate of the last circle's tip is the waveform value at that instant. This value is recorded every frame and drawn on the right side as a 400-point trail:
const trail = trailRef.current
trail.unshift(y)
if (trail.length > TRAIL_LENGTH) {
trail.length = TRAIL_LENGTH
}With 1 term, a single circle rotates and draws a pure sine wave. As terms increase to 5, 10, 20, the epicycle tip traces increasingly complex paths, and the waveform on the right approaches the target shape. For square waves, the process of "becoming angular" is especially dramatic.
Convergence Speed Differences
The mathematical differences between the three waveforms boil down to the decay rate of Fourier coefficients:
| Waveform | Decay | 30-term approximation | Timbre |
|---|---|---|---|
| Square wave | 1/n | Gibbs phenomenon remains | Sharp, hollow |
| Sawtooth wave | 1/n | Comparable to square wave | Rich, bright |
| Triangle wave | 1/n² | Nearly perfect | Soft, round |
A triangle wave is nearly perfect with just 5 terms because higher harmonics are negligibly small. Meanwhile, square and sawtooth waves remain incomplete even at 30 terms, with ringing persisting near discontinuities.
Here lies the connection to timbre: slow convergence = more high-frequency content = brighter, sharper sound. Conversely, fast convergence = less high-frequency content = darker, softer sound. Cutting the high end with a synthesizer filter is exactly the operation of removing higher-order Fourier coefficients.
Gibbs Phenomenon
At the discontinuities of square and sawtooth waves, an overshoot persists no matter how many terms are added. This is the Gibbs phenomenon.
Specifically, an overshoot of about 9% (precisely Si(π)/π - 1/2 ≈ 0.0895) occurs near discontinuities. Adding more terms makes the overshoot "narrower" but doesn't change its "height."
5 terms: ████████████░░░░ Wide overshoot
10 terms: ██████░░ Medium overshoot (same height)
30 terms: ██░ Narrow overshoot (still same height)Mathematically, the Fourier series converges pointwise even for discontinuous functions (converging to the midpoint at discontinuities). However, it does not converge uniformly. Moving the term count slider in the epicycle visualization lets you experience the curious situation where "it converges mathematically, but visually it keeps jittering."
This phenomenon actually causes problems in audio processing. When approximating square waves via Fourier synthesis, the Gibbs phenomenon overshoot can cause clipping and noise. Countermeasures include smoothing techniques like Lanczos sigma approximation (Fejer summation).
Interactive Parameters
The FourierSeries component allows real-time manipulation of four parameters:
- termCount (1-30): Number of Fourier series terms. 1 is just a sine wave; 30 gives a high-precision approximation
- speed (0.1-3.0): Epicycle rotation speed. Slower speeds make each harmonic's contribution easier to see
- waveType: Switch between square / sawtooth / triangle
- showCircles: Toggle epicycle circle display. When hidden, only the tip trajectory is visible
A particularly effective approach is to start at 1 term, observe the waveform, and increase by 1 at a time. For square waves:
- 1 term: Pure sine wave
- 2 terms (n=3): Small undulations appear on the shoulders
- 3 terms (n=5): Top and bottom edges approach flatness
- 5 terms: Fairly rectangular but with rounded corners
- 10 terms: Nearly rectangular, but ringing at the rising edges
- 30 terms: Precise, but discontinuity overshoot persists
Switching wave types calls resetTrail() to clear the trail:
const handleWaveChange = useCallback(
(type: WaveType) => {
playClick()
setWaveType(type)
resetTrail()
},
[playClick, resetTrail],
)This prevents the afterimage of the previous waveform from mixing in.
What I Learned from Implementation
The biggest lesson from implementing Fourier series is that "the frequency domain and the time domain are different views of the same phenomenon."
In the time domain, a waveform appears as "amplitude changing over time." In the frequency domain, the same waveform appears as "the strength of each frequency component." Fourier series is the tool that bridges these two representations.
The fact that timbre is determined by harmonic content is the operating principle of synthesizers. Analog synthesizer "oscillators" generate basic waveforms (square, sawtooth, triangle, sine), "filters" remove specific frequency components, and "envelopes" add time-varying changes. This mechanism can be reproduced in the browser with the Web Audio API. It's essentially the same as manipulating Fourier coefficients.
Epicycle visualization creates the intuitive mapping "one circle = one harmonic." A large circle rotates slowly (fundamental), with smaller circles spinning faster on top (harmonics). The trajectory of the tip of this nested structure is the very waveform of the sound we hear.
What the 402-line component demonstrates is the fact that 200-year-old mathematics remains the foundation of modern audio technology. Without the Fourier transform, there would be no MP3, no JPEG, no Wi-Fi.
Summary: Tools for Fourier Series and Sound Synthesis
For a deep dive into the mathematical background of Fourier analysis and acoustic physics, the books on the tool shelf are excellent starting points. Signal processing introductory texts, in particular, are useful for bridging from the Fourier series covered here to the Discrete Fourier Transform (DFT) and Fast Fourier Transform (FFT).