Skip to content Skip to sidebar Skip to footer

Web Audio Api Plays Beep, Beep,... Beep At Different Rate

I am trying to play 'beep' sound at different rate based on some sensor readings inside a browser window. The idea is to 'beep, beep, beep, ... beep' faster when the sensor reading

Solution 1:

I would most specifically NOT turn an oscillator on and off by connecting and disconnecting it - you'd have to do that from the main thread, so not super-predictable.

You can actually do this with a modulating low-frequency oscillator: check out this code:

var context = new AudioContext();

//defaults to A440Hz, sine wavevar src = context.createOscillator();

// Now let's create a modulator to turn beeps on and offvar mod = context.createOscillator();
mod.type="square";
mod.frequency.value = "2";  // Start at 2Hzvar gain = context.createGain();
var scaler = context.createGain();

src.connect(gain);
gain.connect(context.destination);

mod.connect(scaler); // Mod signal is [-1,1]
scaler.gain.value = 0.5; // we need it to be [-0.5,0.5]
gain.gain.value = 0.5; // then it's summed with 0.5, so [0,1]
scaler.connect(gain.gain);

//start it up
src.start(0);
mod.start(0);

// to change rate, change mod.frequency.value to desired frequency

Post a Comment for "Web Audio Api Plays Beep, Beep,... Beep At Different Rate"