var AudioContext = AudioContext || webkitAudioContext;

var context = new AudioContext();
var sourceBuffer, impulseBuffer;
var convolver;

var analyser = context.createAnalyser();
analyser.fftSize = 256;
analyser.smoothingTimeConstant = .75;
var frequencyData = new Uint8Array( analyser.fftSize );

var canvas = document.createElement( 'canvas' ),
	ctx = canvas.getContext( '2d' );
canvas.width = 1024;
canvas.height = 256;
canvas.style.border = '1px solid #666'
document.body.appendChild( canvas );

function loadSound( src, callback ) {


	var request = new XMLHttpRequest();
	request.open( 'GET', src, true );
	request.responseType = 'arraybuffer';

	request.onload = function() {

		context.decodeAudioData( 
			request.response,
			callback,
			function() {
				console.log( 'error' );
			} 
		);

	};

	request.send();

}

loadSound( 'sound.mp3', function( source ) {

	sourceBuffer = source;

	loadSound( 'cathedral.mp3', function( impulse ) {

		convolver = context.createConvolver();
		convolver.buffer = impulse;
		convolver.connect( analyser );
		analyser.connect( context.destination );

		window.addEventListener( 'click', playSound );

	} );

} );
	
function playSound() {

	var source = context.createBufferSource(); 
	source.buffer = sourceBuffer;
	source.playbackRate.value = .8 + Math.random() * .4;
	source.connect( convolver );
	source.start( 0 );

}

function update() {

	requestAnimationFrame( update );
	analyser.getByteFrequencyData( frequencyData );

	ctx.clearRect( 0, 0, canvas.width, canvas.height );
	for( var j = 0, m = analyser.frequencyBinCount; j < m; j++ ) {
		ctx.fillRect( j * ( canvas.width / m ), canvas.height, .5 * canvas.width / m, - frequencyData[ j ] * canvas.height / 255 );
	}

}

update();