How to Generate and Control Sound within the Browser Using the Web Audio API

How to Generate and Control Sound within the Browser Using the Web Audio API

The Web Audio API is a robust device for creating and controlling sound instantly within the browser. Whether you are constructing video games, interactive media, or experimental music instruments, it presents low-level entry to audio synthesis, results, and spatialization. In this information, you will learn to generate sound, management quantity and pitch, and create primary oscillators utilizing JavaScript.

1. Getting Started With Web Audio

To use the Web Audio API, you must create an AudioContext, which serves as the principle controller for all audio operations.

const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

2. Creating a Simple Tone

To generate a sound, create an oscillator node and join it to the vacation spot (audio system):

const oscillator = audioCtx.createOscillator();
oscillator.kind = 'sine'; // sine, sq., sawtooth, triangle
oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // 440 Hz = A4
oscillator.join(audioCtx.vacation spot);
oscillator.begin();
oscillator.cease(audioCtx.currentTime + 2); // play for two seconds

3. Adding Volume Control

To management the sound’s amplitude (quantity), insert a acquire node between the oscillator and the vacation spot:

const gainNode = audioCtx.createGain();
oscillator.join(gainNode);
gainNode.join(audioCtx.vacation spot);
gainNode.acquire.setValueAtTime(0.5, audioCtx.currentTime); // 50% quantity

4. Making Sound Interactive

Let’s set off a sound on button click on:

<button onclick="playBeep()">Play Beep</button>

<script>
operate playBeep() 
</script>

5. Controlling Pitch and Timing

Use JavaScript intervals to play a sequence of notes:

const notes = [261.63, 293.66, 329.63, 349.23]; // C4, D4, E4, F4
let index = 0;

operate playSequence() 

setInterval(playSequence, 600);

6. Next Steps

  • Add filters and results with BiquadFilterNode or ConvolverNode
  • Build digital devices or synthesizers
  • Record person enter or microphone with MediaStreamAudioSourceNode

Conclusion

The Web Audio API unlocks severe artistic potential for builders concerned with audio. Whether you make a retro synth or an audio visualizer, you now have the instruments to get began.

If this submit helped you, think about supporting me right here: buymeacoffee.com/hexshift

HI-FI News

through DEV Community: javascript https://ift.tt/COLKFD9

April 18, 2025 at 11:12AM