Generating sound on the fly with JavaScript/ HTML5


The Web Audio API is used to control audio, which allows you to choose audio sources. You can also add effects; create audio visualizations, panning, etc.

Example

You can try to run the following code snippet to generate sound −

// use one context per document. Here we are creating one context for one document. You can create for other documents also
var context = new (window.AudioContext || window.webkitAudioContext)();

// oscillator
var os = context.createOscillator();  
os.type = 'sine'; // sine is the default. So you can also use square, saw tooth, triangle
os.frequency.value = 500; // setting the frequency Hz
os.connect(context.destination); // connecting  to the destination

// starting the oscillator
os.start();  
os.stop(context.currentTime + 5); // stop 5 seconds after the current time

Updated on: 24-Jun-2020

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements