Effects can be applied to audio by chaining nodes between the source and the destination node. In this example we use a gain node to mute the source, and only let sound through at specific times. This allows us to create morse code.
function morse(gainNode, pattern) {
let silenceTimeout = 300;
let noiseTimeout;
if(pattern === '') {
//We are done here
return;
} else if(pattern.charAt(0) === '.') {
noiseTimeout = 100;
} else if(pattern.charAt(0) === '-') {
noiseTimeout = 400;
} else {
console.error(pattern.charAt(0), ': Character not recognized.');
return;
}
//Briefly let sound through this gain node
gainNode.gain.value = 1;
window.setTimeout(function() {
gainNode.gain.value = 0;
window.setTimeout(morse, silenceTimeout, gainNode, pattern.substring(1));
}, noiseTimeout);
}
let audioContext = new (window.AudioContext || window.webkitAudioContext)();
let sourceNode = audioContext.createOscillator();
let gainNode = audioContext.createGain();
sourceNode.type = 'sine';
sourceNode.frequency.value = 261.6;
sourceNode.detune.value = 0;
//Mute sound going through this gain node
gainNode.gain.value = 0;
//SourceNode -> GainNode -> Speakers
sourceNode.connect(gainNode);
gainNode.connect(audioContext.destination);
//The source node starts outputting
sourceNode.start();
//Output SOS
morse(gainNode, '...---...');