Basic Web Audio API Example

Just showing off some simple HTML5 Web Audio API stuff

by lq_blocco

HTML

<button id="start-stop">Start/Stop</button><input id="vol" type="range" min="0" value="50" step="1" max="100"/><br/>
<input id="n1" type="number" min="12" value="36" max="60" step="1"/><output id="n1"></output><br/>
<input id="n2" type="number" min="12" value="40" max="60" step="1"/><output id="n2"></output><br/>
<input id="n3" type="number" min="12" value="43" max="60" step="1"/><output id="n3"></output>

JavaScript

var noteNameArray = [
	"C",
	"C#/Db",
	"D",
	"D#/Eb",
	"E",
	"F",
	"F#/Gb",
	"G",
	"G#/Ab",
	"A",
	"A#/Bb",
	"B"
]

var noteOutput1 = document.querySelector("output#n1");
var noteOutput2 = document.querySelector("output#n2");
var noteOutput3 = document.querySelector("output#n3");
var noteInput1 = document.querySelector('input#n1[type="number"]');
var noteInput2 = document.querySelector('input#n2[type="number"]');
var noteInput3 = document.querySelector('input#n3[type="number"]');
var startStopBtn = document.querySelector('button#start-stop'),
	soundActive = false;
var volumeInput = document.querySelector('input#vol[type="range"]'),
	maxVolume = 0.05,
	volumeLevel = maxVolume * volumeInput.value/volumeInput.max;

var noteFrequency = (function(octaveSize, referenceFrequency, referenceNoteNumber) {
	return function(n) {
		return n ? referenceFrequency * Math.pow(2, (n - referenceNoteNumber)/octaveSize) : referenceFrequency;
	}
})(12, 440, 3*12 + 9)

function createOscillatorNode(iElm, oElm, pWave) {
	var oscillatorNode = audioContext.createOscillator();
	//oscillatorNode.type = oscillatorNode.CUSTOM;
	oscillatorNode.setPeriodicWave(pWave);
	
	oElm.textContent = noteNameArray[iElm.value % 12] + ((iElm.value/12)|0);
	oscillatorNode.frequency.value = noteFrequency(iElm.value);
	
	iElm.addEventListener("change", function() {
		oElm.textContent = noteNameArray[iElm.value % 12] + ((iElm.value/12)|0);
		oscillatorNode.frequency.value = noteFrequency(iElm.value)
	})
	
	return oscillatorNode;
}

var audioContext = new AudioContext;

var periodicWave =
	audioContext.createPeriodicWave(
		new Float32Array([0, 1/1, 1/2, 1/4, 1/8, 1/16, 1/32, 1/64]),
		new Float32Array([0, 1/1, 1/2, 1/4, 1/8, 1/16, 1/32, 1/64])
	);

var oscillatorNode1 = createOscillatorNode( noteInput1, noteOutput1, periodicWave );
var oscillatorNode2 = createOscillatorNode( noteInput2, noteOutput2, periodicWave );
var oscillatorNode3 = createOscillatorNode( noteInput3, noteOutput3, periodicWave );

var...