DEV Community

Cover image for A Developer's Guide to the Physics of Sound: Decibels, Hertz, and the Web Audio API
Unitly
Unitly

Posted on

A Developer's Guide to the Physics of Sound: Decibels, Hertz, and the Web Audio API

As developers, we often work with audio, whether it's for notifications, games, or media applications. Understanding the underlying physics of sound, specifically decibels (dB) and hertz (Hz), can be incredibly beneficial, especially when working with tools like the Web Audio API.
What are Hertz (Hz)?
Hertz measures the frequency of a sound wave, which determines its pitch. In the Web Audio API, an OscillatorNode has a frequency property that you can set in hertz.
code
JavaScript
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const oscillator = audioContext.createOscillator();

oscillator.type = 'sine'; // or 'square', 'sawtooth', 'triangle'
oscillator.frequency.setValueAtTime(440, audioContext.currentTime); // A4 pitch
What are Decibels (dB)?
Decibels measure the loudness of a sound. It's a logarithmic scale, which is important to remember when programming audio. A small change in decibels can mean a large change in perceived loudness. In the Web Audio API, you control this with a GainNode.
code
JavaScript
const gainNode = audioContext.createGain();
gainNode.gain.setValueAtTime(0.5, audioContext.currentTime); // Set volume to 50%
Practical Applications
Understanding these concepts is crucial for:
Creating realistic sound effects in games.
Building audio visualizations and equalizers.
Ensuring accessibility by controlling audio levels.
For anyone needing to quickly convert between various sound and frequency units, I've found the tools at www.unitly.info to be incredibly helpful. It's a great resource for any developer working with audio.

Top comments (0)