How to generate synthetic sound with mathematics
This blog is based on my learnings from a recent contribution to the beui wheel-picker element, where I proposed an idea to add a 'tick' sound whenever the wheel scrolls.
this blog is mostly the theory side how we can approach this problem, for code you can refer to my PR on GitHub
Whenever we need a sound in our web application, the obvious thought that comes to our mind is to add an mp3 file. But what if there's a better way?? If you could generate sound at runtime through pure mathematics?
This is exactly what the browser's audio API allows us to do, and in this PR we created a synthetic sound entirely at runtime using sine waves, noise, decay, and a few hundred calculated noise samples.
On a high level, this is the complete journey:
Mathematics → Digital samples → Browser audio system → Speaker vibration → Sound
Physical world scenario
When we hit an object, the impact makes it vibrate, that vibration pushes and pulls the surrounding air, creating a change in air pressure. Those pressure waves eventually reach our ears, and our brain interprets them as sound.
A simplified version:
Impact → Vibration → Air pressure waves → Ear → Sound
The thing of our concern over here is vibration.
If something vibrates 1,000 times every second, we say that it has a frequency of 1,000 Hz or 1kHz.
Since we can describe these vibrations mathematically, we can attempt to create them through code.
Simplest sound - sine wave
A sine wave smoothly moves between positive and negative values:
So if we create this wave 1000 times every second, we get a 1000Hz tone. Mathematically, it can be written as sin(2πft), which tells us how a value changes between -1 and 1.
If we send this waveform to a speaker, we get a sound. Now the problem is that pure sine waves sound very electronic, like "Beep..."; for our utility, we need a more mechanical sound. Fine-tuning towards a real sound simulation.
Actual objects vibrate at multiple frequencies
You may've noticed that when any real-world object gets hit, it just doesn't vibrate on a single frequency, but it contains multiple frequencies. These natural vibration patterns are called "resonant modes".
So to make our mathematical sine wave sound more natural, we'll put multiple frequencies into it, e.g., 980 Hz, 1820Hz, 3160Hz. These are purely random numbers; just to note that they shouldn't be in direct multiples of each other.

