// Guy Fernando (2020).
// A simple audio frequency signal generator using Mozilla web audio.
//
class SignalGenerator {
// Default constructor.
//
constructor(freq, ampl, wave) {
this.freq = freq;
this.ampl = ampl;
this.wave = wave;
this.mute = false;
var AudioContext = window.AudioContext || window.webkitAudioContext;
let a = new AudioContext({
latencyHint: 'interactive',
sampleRate: 44100
});
// Create nodes.
this.o = a.createOscillator();
this.g = a.createGain();
// Set parameters.
this.g.gain.value = this.ampl / 1000.0;
this.o.frequency.value = this.freq;
this.o.type = this.wave;
// Connect
this.o.connect(this.g);
this.g.connect(a.destination);
// Schedule tone.
this.o.start();
}
// Set audio frequency.
//
setFreq(freq, range, callback) {
this.freq = freq;
this.range = range;
this.o.frequency.value = parseFloat(this.freq) * Math.pow(10, parseInt(this.range));
// Callback frequency result in Hz.
callback(this.o.frequency.value);
};
// Set audio amplitude.
//
setAmpl(ampl, callback) {
this.ampl = ampl;
if (this.mute === false) {
this.g.gain.value = this.ampl / 1000.0;
}
// Callback amplitude result in percent.
callback(Number(this.ampl).toFixed(0));
};
// Set audio waveform.
//
setWave(wave) {
this.wave = wave;
this.o.type = this.wave;
};
// Set audio mute state.
//
setMute(mute) {
this.mute = mute;
if (this.mute === true) {
this.g.gain.value = 0;
}
else {
this.g.gain.value = this.ampl / 1000.0;
}
}
// Get audio frequency result in Hz.
//
getFreq() {
return this.freq;
}
// Get audio amplitude result in percent.
//
getAmpl() {
return Number(this.ampl.toFixed(0));
}
// Get audio waveform.
//
getWave(wave) {
return this.wave;
};
}
This javascript class shown here further simplifies the process of generating simple “sine”, “square”,
"sawtooth" or “triangle” waveforms, with a specified frequency and amplitude. The signal generator above
on this page invokes calls to this class library enabling all the functions on the signal generator to be
played by the hardware.