Skip to content Skip to sidebar Skip to footer

Cross Browser Html5 Javascript Generate Single Tick Sound

I need a single-shot square wave of approximately 20 ms width. I have not found a simple autonomous code sample to do this. Without external libraries and with only a couple of lin

Solution 1:

The Web Audio API provides a set of interesting tools for audio processing which I've used to produce a 226.6hz 20ms square wave below.

Update Web Audio oscillator notes can only be started and stopped once. This is a design flaw feature that requires creating a new ocillator node each time one is played.

I've also included master and oscillator gain controls so show interconnection of audio nodes.

// create audio context, masterGain and nodeGain1 nodesvar audioContext = new (window.AudioContext || window.webkitAudioContext)();
//  ( "Webkit/blink browsers need prefix, Safari won't work without window.")var masterGain = audioContext.createGain();
    masterGain.gain.value = 0.5;
masterGain.connect(audioContext.destination);

var nodeGain1 = audioContext.createGain();
    nodeGain1.gain.value = 0.5;
nodeGain1.connect(masterGain);

functionclickBuzz( frequency, length) {
    var oscillatorNode = newOscillatorNode(audioContext, {type: 'square'});
    oscillatorNode.frequency.value = frequency;
    oscillatorNode.connect( nodeGain1);
    oscillatorNode.start(audioContext.currentTime);
    //setTimeout( function(){oscillatorNode.stop();}, length*1000);
    oscillatorNode.stop( audioContext.currentTime + length);
}

functionvolume1( rangeInput) {
    masterGain.gain.value = +rangeInput.value;
}

functionvolume2( rangeInput) {
    nodeGain1.gain.value= +rangeInput.value;
}
<p>Type in the textarea for keypress sounds:</p><textareaonkeydown="clickBuzz( 261.6, 0.020)"></textarea><p><inputtype="range"min="0"max="1"step="0.01"value="0.5"style="width: 200px"onchange="volume1(this)"onkeypress="volume1(this)"> master volume
</p><p><inputtype="range"min="0"max="1"step="0.01"value="0.5"style="width: 200px"onchange="volume2(this)"onkeyup="volume2(this)"> oscillator volume
</p>

The above code works in Firefox and Chrome, and MDN provides more information on browser compatability.

The timing accuracy of starting and stopping oscillators with the code as written is of concern: it sometimes abbreviates or drops click sounds. Possibly start starts playing sound asynchronously and any accumulated delays in starting to play are coming out of total play length, but I have not fully investigated the issue (setTimeout was less prone to the problem than stop).

Post a Comment for "Cross Browser Html5 Javascript Generate Single Tick Sound"