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

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 () {

	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;[index + 0] = RGBA;[index + 1] = RGBA;[index + 2] = RGBA;[index + 3] = RGBA;
	textureContext.putImageData(textureImage, 0, 0);

	// Set the texture
	if(!window['gl']) return;

	var texture = gl.createTexture();
	gl.bindTexture(gl.TEXTURE_2D, texture);
	gl.texImage2D(gl.TEXTURE_2D, 1, textureCanvas);

window.setTimeout( drawSoundData, 1000 / 60 );

Even more barebones CAAT Template

Similar to a previous post, where I provided a basic template for my CAAT circle-collision manager, i wanted to provide the most utterly basic hello-world template possible for CAAT that does almost nothing except put initialize and draw a single object.

You can find that here:
(Select downloads, and select EntryPoint)

What is a closure

Was talking with a coworker explaining what a bit of javascript syntax was doing, and reminded me of a good explanation of what a closure is in Javascript.

The short version of it is that:
A closure, enCLOSES all the variables – allowing you to access them from anywhere within that… enCLOSURE

This is because javascript only has one kind of scope, function scope.
Everything inside of a function has access to the created by the parent function.
So you can have something like this

var CanvasDemo = function() {
		return this;

// On Ready Callback
	CanvasDemo.onReady = function(e)
		this.canvas = this.createCanvas();
		this.canvasContext = this.canvas.getContext('2d');
		this.canvasContext.fillRect(100, 100, 50, 50);


		// Start rendering loop
		var that = this;
		this.loopInterval = setInterval(function() {
                 console.log(this); // 'this' - refers to document window
                 console.log(that); // 'that' - refers to 'CanvasDemo' instance
		}, 30);

Because the closure (created by the javascript engine in the background), enCLOSES the ‘that’ variable, the function maintains access to it.


CAAT is short for Canvas Advanced Animation Toolkit. It is written by @hyperandroid, the code itself is a dream to look thru. Its insanely well written, and whats more greater is that it’s even faster than it is nicely written!

I used it for, which I plan on writing about a little bit more in the future. Because I liked CAAT so much, and it saved my butt on that project, I wanted to contribute back to it, so I have added my simple CircleCollisionManager class back into it.

Base template

I wanted to create the most basic shell, in order to get it up and running with something displaying on the screen. So I have shared the source for the code below which i tried to keep as succinct as possible.

Most basic helloworld with CAAT

Here is the code for that:

I tried my best to make it have code that contains enough useful functions that show off a few CAAT features, without getting too far beyond HelloWorld.

Perfect example of whats wrong with JS

This is from the Require.js library which is very useful, and solves a lot of find when using JS.

    //Alias for caja compliance internally -
    //specifically: "Dynamically computed names should use require.async()"
    //even though this spec isn't really decided on.
    //Since it is here, use this alias to make typing shorter.
    req = require;


Use this alias to make your development time noticeably shorter by doing that? Are you really clocking out earlier? Calling it a half day most of the time after that huge time saver?

No it’s just a pointless and at worst confusing inconsistent modification to the code from only that point forward to anyone looking at it.

Another Example

This also irks me. I’m getting some error, and im trying to dive into the multi-thousand line (literally) file, and figure out whats going wrong / learn the module better. When I go to the line in question, i scroll up to find this:

 main = function (name, deps, callback, config, contextName, relModuleName) {
        //Grab the context, or create a new one for the given context name.
        var context, newContext, loaded, pluginPrefix,
            canSetContext, prop, newLength, outDeps, mods, paths, index, i,
            deferMods, deferModArgs, lastModArg, waitingName, packages,

        contextName = contextName ? contextName : (config && config.context ? config.context : s.ctxName);

// What the freaking hell is s?       
context = s.contexts[contextName];

        if (name) {
                        // Pull off any plugin prefix.
            index = name.indexOf("!");
            if (index !== -1) {
                pluginPrefix = name.substring(0, index);
                name = name.substring(index + 1, name.length);
            } else {
                //Could be that the plugin name should be auto-applied.
                //Used by i18n plugin to enable anonymous i18n modules, but
                //still associating the auto-generated name with the i18n plugin.

//				console.log(" context.defPlugin[name]", this);
                pluginPrefix = context.defPlugin[name];

            //If module already defined for context, or already waiting to be
            //evaluated, leave.
            waitingName = context.waiting[name];
            if (context && (context.defined[name] || (waitingName && waitingName !== ap[name]))) {

What the hell is ‘s’? !! This left my struggling to find it by doing ctrl+f, for the most popular letter in the alphabet.

Seriously i waste so much time on this kind of junk when I code in javascript – it really takes the fun of it.

“Using JS.Class” or “Sharing a Class Between Node.JS and the Browser Part 2”

Just a quick snippet, but this is a much better way of sharing a class between Node.js and the browser. I also like this psuedo Class implementation much better than the Class.js thing, it always seemed a bit ghetto how you had to say.

The ugly way (i was using this before but it felt wrong)

var ServerGame = require('./ServerGame.js').Class;

var myInstance = new ServerGame();

There’s a better way!

 * Animal.js
 * This is an example I created for us JS.Class
 * Mario Gonzalez |
var init = function()
	return new JS.Class(
		initialize: function(name) { = name;
			console.log( 'Animal::initialize - ', name);

		 * Cause the Animal to tell you what it likes (Testing JavaDoc)
		 * @param things What the animal likes
		speak: function(things) {
			return 'My name is ' + + ' and I like ' + things;

// Handle Node.JS and browser
if (typeof window === 'undefined') {
	Animal = init();
} else {
	define(['lib/jsclass/core'], init);

Ok, but now to use it in another file!

// Testing JS.Class

// bring it in

// use it
var animal = new Animal('Rex');
console.log('Animal', animal.speak("YELLING!!!") ); // Should output: Animal My name is Max and I like BARKING!!!

There you have it – so simple and soooo much cleaner!!