Skip to content

Instantly share code, notes, and snippets.

@notthetup
Created April 7, 2014 07:34
Show Gist options
  • Save notthetup/10016138 to your computer and use it in GitHub Desktop.
Save notthetup/10016138 to your computer and use it in GitHub Desktop.
Testing WebAudioAPI Delay precision
"use strict";
var AudioContext = webkitAudioContext || AudioContext;
var context = new AudioContext();
var length = 44100;
// 2 Buffers to hold samples
var bufferSourceNode = context.createBufferSource();
var counterNode = context.createBufferSource();
// Scope to see what's going through
var scopeNode = context.createScriptProcessor();
var delayNode = context.createDelay();
// Delay by a single sample
delayNode.delayTime.value = 1.0/44100;
// Create counter buffers - monotonically increasing values
counterNode.buffer = createCounterBuffer( length );
bufferSourceNode.buffer = createCounterBuffer( length );
// Scope callback
scopeNode.onaudioprocess = printPosition;
// Hook up one buffer through delay
bufferSourceNode.connect(delayNode);
delayNode.connect(scopeNode);
counterNode.connect( scopeNode );
scopeNode.connect(context.destination);
//Start
counterNode.start(0);
bufferSourceNode.start(0);
// Prints the first sample of each frame.
// Each sample is the sum of the two counter buffers
// So the value of the sample will indicate where the buffer
// is being played from.
function printPosition( processEvent ) {
var inputBuffer = processEvent.inputBuffer.getChannelData( 0 );
console.log(inputBuffer[ 0 ]);
}
// Create motonically increasing, 1,2,3,4...
// buffer to be used to figure out the
// current playing position of a delayed buffer.
function createCounterBuffer( length ) {
var array = new Float32Array( length );
var audioBuf = context.createBuffer( 1, length, 44100 );
for ( var index = 0; index < length; index++ ) {
array[ index ] = index;
}
audioBuf.getChannelData( 0 )
.set( array );
var inputBuffer = audioBuf.getChannelData( 0 );
//console.log("S " + inputBuffer[ inputBuffer.length -1 ]);
return audioBuf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment