Skip to content

Sound with JavaScript: Making Sounds Without a Single Audio File

Published on · Joaquín Dati

If you open my portfolio’s intro with sound on, you’ll hear a meteor whooshing by, a breathing space ambience, radio static and even the characters’ “voices”. The fun part is that there isn’t a single audio file behind it: everything is generated in the browser, in real time, with JavaScript.

The idea: the browser as a synthesizer

Browsers ship with a tool called Web Audio. It works like a tiny sound studio: there are tone generators (oscillators), noise generators, filters that let lows or highs through, and volume controls. Wiring them together like cables on a mixing desk, you can create almost any sound.

An example to try

Open your browser console (F12), paste this and press Enter:

const ctx = new AudioContext();
const tone = ctx.createOscillator();
const vol = ctx.createGain();
tone.frequency.value = 440;
tone.connect(vol).connect(ctx.destination);
vol.gain.setValueAtTime(0.3, ctx.currentTime);
vol.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 1);
tone.start();
tone.stop(ctx.currentTime + 1);

You’ll hear a “ping” that fades out in a second. Change 440 to 110 and it gets deep; switch the waveform with tone.type = "square" and it sounds like a retro video game. Piece by piece, that’s how instruments are built.

The intro’s recipes

Every sound in the portfolio is a recipe made from these pieces:

  • The meteor: filtered noise whose pitch drops as it moves away, imitating the effect you hear when an ambulance drives past.
  • The space ambience: three low tones slightly out of tune with each other and a filter that slowly opens and closes, so it “breathes”.
  • The characters’ voices: synthesis that imitates human vowels, with no real words, in the style of classic video game characters.

Sounds are also placed in 3D space: if an object is on your left, you hear it on your left.

Why do it this way

Sounds generated on the fly weigh nothing to download, can react to what’s happening on screen, and never sound exactly the same twice. It’s a way to bring a website to life that very few sites take advantage of.