WebAudio and WebMIDI Experiments
Support for the Web Audio API is not the same in all browsers. If you have trouble playing the examples, try using Chrome.
Custom Node
Use a ScriptProcessorNode to generate an algorithmic sound. This is a minimal example.
Roll mouse over this paragraph to play noise.
status messages
JavaScript code for the sound generator. It uses "webaudio_tools.js".
// Example showing how to produce a tone using Web Audio API.
var customNode = 0;
// Variables used to control the custom Node
var kBufferSize = 0; // let the audio system decide on the buffer size
// var kBufferSize = 256; // must be power of 2 >= 256
var kNumInputs = 0; // no input
var kNumOutputs = 2; // stereo output
// Use a ScriptProcessorNode to generate a custom audio signal.
function initAudio() {
// Use audioContext from webaudio_tools.js
if (audioContext) {
customNode = audioContext.createScriptProcessor(kBufferSize, kNumInputs, kNumOutputs);
customNode.onaudioprocess =
// This function will be called repeatedly to fill an audio buffer and
// generate sound.
function (e) {
// Get array associated with the output ports.
var left = e.outputBuffer.getChannelData(0);
var right = e.outputBuffer.getChannelData(1);
var n = output.length;
for (var i = 0; i < n; ++i) {
// random() returns a value that is [0,1)
// output must be [-1,1)
left[i] = (Math.random() * 2.0) - 1.0;
right[i] = (Math.random() * 2.0) - 1.0;
}
}
writeMessageToID( "soundStatus", "<p>Audio initialized.</p>");
}
}
// Start the node by connecting it into the graph.
function startSound() {
customNode.connect(audioContext.destination);
writeMessageToID( "soundStatus", "<p>Start sound.</p>");
}
function stopSound() {
customNode.disconnect(audioContext.destination);
writeMessageToID( "soundStatus", "<p>Stop sound.</p>");
}
// Initialize once the page has finished loading.
window.onload = initAudio;