Variable responsibility cycle sq. waves with the Web Audio API

Variable responsibility cycle sq. waves with the Web Audio API

Created on 4/2/2025Updated on 4/2/2025

Lately, I’ve been enjoying round with the Web Audio API for a facet challenge I’m engaged on. I’m constructing a web-based music tracker software program for creating audio within the unique model of the Gameboy. To faithfully recreate the sounds of the Gameboy, I would like variable responsibility cycle sq. waves.

The iconic 8-bit, chiptune model of music is closely reliant on sq. waves. The Web Audio API means that you can create OscillatorNodes that symbolize periodic waveforms like a sine, sawtooth, triangle, or sq. waves.

const ctx = new AudioContext(); const osc = new OscillatorNode(ctx, { kind: "sq.", });

Here is what an A4 appears like with a 50% responsibility cycle sq. wave:

Not essentially the most nice musical factor you’ve got ever heard however you get the gist.

Seems like we now have our sq. wave, fairly simple proper? Unfortunately no, not fairly. Oscillators with the sort "sq." solely enable for an obligation cycle of fifty%. This implies that for one cycle, the wave is excessive for half the time and low for the opposite half.

One of the neat issues concerning the Gameboy was that its two pulse channels allowed for variable responsibility cycles. Specifically, the responsibility cycle could possibly be set to 12.5%, 25%, 50% or 75%. This allowed recreation builders to create richer, extra textured sounds for his or her video games.

To get round this 50%-duty-cycle limitation of the Web Audio API, I needed to discover a technique to create sq. waves from a unique kind of periodic waveform.

We have a few choices. One method is to make use of the Fourier Series. Another is to make use of a WaveShaperNode to bend a sawtooth wave into the specified responsibility cycle sq. wave. First, let’s check out the Fourier Series.

The Fourier Series Approach

In brief, the Fourier Series is a technique to symbolize a periodic perform or waveform as an infinite sum of sines and cosines. It is like increase waves from harmonics like lego bricks. Basically, we will perform a little little bit of math to create a periodic waveform that we will form an OscillatorNode‘s output with. The Web Audio API exposes a perform on the AudioContext that we will use to create a periodic waveform from a set of Fourier coefficients. This is how that appears.

// Create your audio context & oscillator const ctx = new AudioContext(); const osc = new OscillatorNode(ctx); osc.frequency.worth = 440; // A4 = 440Hz // Configure your required responsibility cycle & variety of harmonics const dutyCycle = 0.25; const harmonics = 64; // More harmonics = extra correct sq. wave // Create arrays for actual and imaginary elements of Fourier coefficients const actual = new Float32Array(harmonics); const imag = new Float32Array(harmonics); // DC offset (common worth primarily based on responsibility cycle) actual[0] = 2 * dutyCycle - 1; imag[0] = 0; // Calculate harmonic amplitudes for desired responsibility cycle for (let n = 1; n < harmonics; n++) { // Cosine phrases are zero for sq. waves actual[n] = 0; // Sine phrases comply with this formulation for responsibility cycle D: imag[n] = (2 / (n * Math.PI)) * Math.sin(n * dutyCycle * Math.PI * 2); } // Create a periodic wave from our Fourier coefficients const wave = ctx.createPeriodicWave(actual, imag, { disableNormalization: false }); // Set the oscillator to make use of our customized wave osc.setPeriodicWave(wave);

Now we now have a sq. wave oscillator with an obligation cycle of 25% or no matter we want to set it as.

Here is what sq. waves with variable responsibility cycles sound like when created with the Fourier Series method.

This method is a bit more math heavy than the following – the following technique is slightly bit extra intuitive to understand.

The WaveShaper Approach

The Web Audio API gives us with a technique to distort alerts. This is the WaveShaperNode. When creating audio with the Web Audio API, you join audio nodes in a graph. Typically will probably be one thing like this:

OscillatorNode → GainNode → AudioDestinationNode

The WaveShaperNode lets us remodel the output from one thing like an OscillatorNode. We can do a enjoyable little factor with a sawtooth wave the place we create a step perform to bracket the worth to both 0 or 1 relying on the place it falls in relation to the responsibility cycle level.

const ctx = new AudioContext(); const osc = new OscillatorNode(ctx, { kind: "sawtooth", }); const dutyCycle = 0.125; // Create the waveshaper const waveShaper = new WaveShaperNode(ctx); // Create the switch perform that shapes the wave const curveLength = 2048; const curve = new Float32Array(curveLength); // The magic occurs right here - create a step perform on the responsibility cycle level for (let i = 0; i < curveLength; i++) { const x = i / (curveLength - 1); // Normalize to 0-1 vary curve[i] = x < dutyCycle ? 1.0 : -1.0; // Step perform } waveShaper.curve = curve; oscillator.join(waveShaper);

From right here, we will join the waveShaper to an output node and now we now have a sq. wave of no matter responsibility cycle we like. I favor this method due to how easy and simple it’s to understand.

Here is what sq. waves with variable responsibility cycles sound like when created with the Waveshaper method.

You may discover that the sq. waves created with the Waveshaper method sound "buzzier" than the Fourier Series method. This is as a result of the Waveshaper method creates an virtually mathematically good sq. wave with extraordinarily sharp transitions.

There are execs and cons to every method. One of the cons of the Fourier Series method is that you just want a variety of harmonics for it to sound respectable, which is expensive in CPU cycles. This is very true in case your software helps any responsibility cycle between 0% and 100% and calculates the curve on the fly. The good factor concerning the music tracker software program that I’m engaged on is that I solely must help 4 responsibility cycles so I can compute my waveShaper curves as soon as forward of time and reuse them all through the applying. One of the downsides of the Waveshaper method is that you just begin working into aliasing and buzziness.

For my functions, the Waveshaper method is my most popular technique. I just like the simplicity of it and I additionally imagine that it creates a extra genuine Gameboy sound. This is simply the tip of the iceberg because it pertains to the Web Audio API – I actually do suppose there’s a variety of potential for constructing cool issues with this software and extra devs ought to test it out.

HI-FI News

by way of Hacker News https://ift.tt/nPG6mOJ

April 7, 2025 at 06:37PM