Using SoundManager2 to create a texture of EQ spectrum data via javascript

I couldn’t find a snippet to fill a 256px size audio texture so I thought I would share mine incase it helps anyone:

View Demo

http://onedayitwillmake.com/blog/wp-content/uploads/2011/06/audiotexture/AudioTexture.html

Code Sample

function initSoundObject() {
	soundManager.flashVersion = 9;
	soundManager.url = '../../swf/';
	soundManager.useHighPerformance = true;
	soundManager.debugMode = true; // disable debug mode
 
	// When soundmanager has finished loading, loud our mp3
	soundManager.onready(function() {
	  // Ready to use; soundManager.createSound() etc. can now be called.
		soundObject = soundManager.createSound({
			id: 'mySound',
			url: 'img/ModulaScren-thisiswhoweare.mp3',
			autoLoad: true,
			autoPlay: true,
			usePeakData: false,
			useWaveformData: false,
			useEQData: true,
			volume: 50
		});
	});
}
 
var drawSoundData = function () {
	if(!soundObject)
		return;
 
	var textureWidth = 256;
	var textureHeight = 64;
	var textureCanvas = document.getElementById("dotc");
//	var textureCanvas = document.createElement("canvas");
	textureCanvas.width = textureWidth;
	textureCanvas.height = textureHeight;
	var textureContext = textureCanvas.getContext("2d");
	var textureImage = textureContext.getImageData(0, 0, textureWidth, textureWidth);
 
	var len = soundObject.eqData.left.length;
	for( var k = 0; k < len; k++ ) {
		// Set the RGBA data for this pixel - note: +soundObject.eqData.left[i] 
                // is just a unary operation to convert to a number
		var spectrumValue = (+soundObject.eqData.left[k] + +soundObject.eqData.right[k]) / 2.0;
			for (var j = 0; j < textureHeight; j += 1) {
				var column = k;
				var index = (j * textureWidth + column) * 4;
				var RGBA = spectrumValue * 255;
				textureImage.data[index + 0] = RGBA;
				textureImage.data[index + 1] = RGBA;
				textureImage.data[index + 2] = RGBA;
				textureImage.data[index + 3] = RGBA;
			}
		}
	textureContext.putImageData(textureImage, 0, 0);
 
	// Set the texture
	if(!window['gl']) return;
 
	var texture = gl.createTexture();
	gl.activeTexture(gl.TEXTURE0);
	gl.bindTexture(gl.TEXTURE_2D, texture);
	gl.texImage2D(gl.TEXTURE_2D, 1, textureCanvas);
	gl.generateMipmap(gl.TEXTURE_2D);
};
 
window.setTimeout( drawSoundData, 1000 / 60 );

4 thoughts on “Using SoundManager2 to create a texture of EQ spectrum data via javascript”

  1. Do you think it would be possible for you to look at my basic Soundmanager2 code? For some reason it is not scanning for the eqData even though flash is installed and enabled for the webpage and useEQData is on for the sound. Any tips would be great, but I know this post is quite old so I’d be fine if I didn’t get a response. Here’s the code: http://pastebin.com/WkzkECcS

Leave a Reply

Your email address will not be published. Required fields are marked *


*