3
votes

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 is high, and "beep,...beep" slower when the sensor reading is low, all in real-time.

The sensor reading is fed into the browser via socket.io. I can already control a progress bar moving up and down. The audio feedback is an extra feature.

After some googling, I am thinking about using web audio api, creating a sin-wave oscillator, and to turn it on/off with a gain node connect/disconnect.

My question is how do I control the timing in the right way, say I am trying to beep at a range of frequencies from 1 Hz to 20 Hz, and be able to change the frequency dynamically.

1
Please clarify frequency in terms of your question -- there is the fundamental frequency of your sine wave (the pitch of the beep) but you also make reference to faster and slower beep repetitions which could also be considered a frequency. Are you trying to modulate just the rate of the repeating beeps or also the pitch?David Tansey

1 Answers

9
votes

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 wave
var src = context.createOscillator();

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

var 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