Web Audio
Audio Node Types
- Source Nodes - audio buffers, live inputs,
<audio>
tag, ocillators, JS Processors. - Modification Nodes - Filters, Convolvers, Panners, JS Processors.
- Analysis Nodes - Analyzers, JS Processors.
- Destination Nodes - Audio outputs and offline processing buffers.
Create Context
var contextClass = (window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.oAudioContext || window.msAudioContext);
if (contextClass) { // Web Audio API is available.var context = new contextClass();} else { // Web Audio API is not available. Ask the user to use a supported browser.}
Connect Context
// Create the source.var source = context.createBufferSource();
// Create the gain node.var gain = context.createGain();
// Connect source to filter, filter to destination.source.connect(gain);gain.connect(context.destination);
// Disconnectsource.disconnect(0);gain.disconnect(0);source.connect(context.destination);
Modular Routing
- Sound Waves
- Digital Sound
- Sample Rate
- Bit Depth
- Bit Rate
- Quantization
- PCM - Pulse code modulation.
AudioBuffer
is an array of PCM data. - Audio Encoding Formats - FLAC(lossless) guaranteed bit to bit restore, MP3(lossy)
Loading and Playing Sounds
var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer';
// Decode asynchronously request.onload = function() { context.decodeAudioData(request.response, function(theBuffer) { buffer = theBuffer; }, onError);}
request.send();
function playSound(buffer) { var source = context.createBufferSource(); source.buffer = buffer; source.connect(context.destination); source.start(0);}
Timing Model
Not used in web audio.
setTimeout()
setInterval()
- new
Date()
window.performance.now()
Used
- AudioContext.
currentTime
Playback of web audio is in float
seconds not integer milliseconds.
Simple Sequencer
This sequencer adds all notes at the start and does not use a time window for dynamic sequencing. Once the events are sequenced natively, you cannot remove them.
for (var bar = 0; bar < 2; bar++) { var time = startTime + bar * 8 * eighthNoteTime; // Play the bass (kick) drum on beats 1, 5 playSound(kick, time); playSound(kick, time + 4 * eighthNoteTime); // Play the snare drum on beats 3, 7 playSound(snare, time + 2 * eighthNoteTime); playSound(snare, time + 6 * eighthNoteTime); // Play the hihat every eighth note. for (var i = 0; i < 8; ++i) { playSound(hihat, time + i * eighthNoteTime); }}
Changing Audio Parameters
setValueAtTime()
setValueCurveAtTime()
// Create a gain node. var gainNode = context.createGain();
// Connect the source to the gain node. source.connect(gainNode);
// Connect the gain node to the destination. gainNode.connect(context.destination);
// Reduce the volume. gainNode.gain.value = 0.5; // OR gainNode.gain.setValueAtTime(0.5, context.currentTime + 1);