The Seven Stages of Learning Dojo

Filed in development | dojo | html5 | javascript | ui | web Leave a comment

So, yah I’m learning Dojo, though from what I’ve heard this could easily apply to ExtJS.  It’s a different mindset to get accustomed to an enterprise Javascript framework, and comes with a bit of a steep learning curve.

And, so it begins….

“Ooooooh look at all these awesome features on http://dojotoolkit.org!  They have a hot themetesterfull documentation for like every single part of their toolkit.  And GLORIOUS quickstarts!

1. Shock and Denial

“WTF, I’ve copied this code EXACTLY, but it spews tons of errors, and doesn’t even come close to working.”

“I’ve looked up all these error messages, but I can’t find a straightforward answer.  Everyone references concepts I’m not familiar with….and they keep telling me to hop on an IRC channel to talk to the developers.  Is IRC still a thing?  Do they have a BBS as well?  Maybe I can learn the language of my 14.4 kilo-baud modem and ask IT how to do stuff in Dojo by chriping and clicking at it”

“It’s gotta be me….I’m an idiot, it can’t be this difficult to get basic stuff working”

2. Pain and Guilt

“Screw, it – let’s man up and just read massive quantities of documents and tutorials.  Hell, I’m going to buy a book from 2008 even thought it’s horribly out of date.  I’m just going to sit through this initial pain to get a better understanding of the whole system.”

“Am I really this dumb?”

3. Anger and Bargaining

“Dojo SUCKS, I hate it!  It doesn’t work. I need to be a freakin rocket scientist to understand this system”

“jQuery, will you take me back?  Please?  I just want some data stores, and some binding, and some well written and documented plugins.”

4. Depression, Reflection, and Loneliness

“So lonely….the only materials I see online are from 2008, and from SitePen who charges for training, why would they help and give it all away for free?”

“Maybe if I had studied harder in school, this wouldn’t be a problem”

5. The Upward Turn

“Going back to the beginning and reading a bunch of stuff seems to have paid off, I think I’m beginning to understand now”

“Where in the hell did they tell you about this parseOnLoad attribute in the script tag?  It’s not in any of the quickstart examples, but it’s freaking mandatory to get anything to work”

“Well, no WONDER, this example didn’t work, it was written in Dojo 1.6 before the AMD Loader, and I’m mixing and matching my code between 1.6 and 1.7 – and 1.7 has REALLY changed the game”

“Ahhhhhh…..I need to nest the requires, cause my require doesn’t know what the ready object is before it loads the core stuff”

6. Acceptance and Hope

“Now that I understand the basics, I really like Dojo.  It rocks pretty hard!”

“There are things I don’t yet understand, but now that I have the big picture, I can roll with anything Dojo can throw at me, but all in all, I’m very psyched about all these new toys!”

7. Reconstruction and Working Through

“Dude, did I really just wire up a data store to a div which I made into a repeater, all inside a freaking accordion?  Damn….awesome”

“I made a build system, and moved all my layers somewhere else, so I’m completely relying on my own custom build….I only get like 2 errors, and none of them block functionality.  This will get better, but for now, it’s awesome enough”

Fin

And here I am.  Though, I think I cycled through steps 3, 4, and 5 a few times.

Why Dojo? From a Flash/Flexer’s Perspective

Filed in development | dojo | flash | flash/flex | flex | html5 | javascript | ui 5 Comments

Hey you guys…  Is your Twitter stream bombarded with Ted Patrick tweets and retweets about Sencha?  Do you get Sencha ads targeted at you when you visit websites, like EVERYWHERE you go?

I am.  It’s kind of annoying since I’m not looking to learn Sencha.  Truthfully, though, you can hardly blame the current Sencha evangelist.  After Adobe abandoned Flex sending it off to Apache, Ted seems to be leading a HUUUUUUGE marketing push trying to turn former Flex devs into Sencha/ExtJS devs.  Ted is leading webinars, reaching out to people, posting on G+ threads, the whole deal.

I can hardly blame him because:

a) I follow him on Twitter, so it’s mostly my own damn fault

b) This is the perfect time to grab a bunch of disillusioned and lost Flex devs, and Ted is doing it in a perfectly ethical (although a bit overzealous way).

I looked into going “beyond” jQuery because of a G+ post by Jesse Warden claiming that ExtJS is the perfect compliment to enterprise development.  He made the very apt analogy that Flash is to jQuery as Flex is to ExtJS/Sencha.  It really made me re-think things because it had been drilled into my brain that jQuery “won”, and given the tide of developers (84.8% of all websites using a library use jQuery) it seemed like there was no reason to use anything else.

Turns out, there really is a use for the lesser used libraries/frameworks/toolkits.  We can see this because even if jQuery is and always will be your library of choice, as you build more advanced applications you might want some binding, templating, MVC, or other action.  AngularJS by Google is getting more widely used.  It gives you binding, declarative HTML markup for data, and other MVC goodies.  There’s Backbone.JS, Underscore.JS, and tons of others.  A lot of folks seem to be combining all of these separate libraries together to custom fit their project.  And I’m sure that works fantastically – I was doing similar things for a time.

As these separate projects get more and more features, you may now have feature overlap between 3 different libraries you’ve used in your project.  It seems a LITTLE wasteful at best.  At worst, maybe your dev team does a very basic thing 3 different ways because binding is available 3 different ways given each of the libraries you’re using.

Wouldn’t it be better, or even just worth looking into, if you could find a cohesive library/framework that offered all of these things together? Maybe it could even do a little more and help you make a massive Javascript application that loaded in components and scripts AS YOU NEED THEM instead of all at once in the beginning.

It looked like Dojo and ExtJS were the most mature offerings in terms of what I describe.  I took a look at ExtJS by Sencha first.  At first glance, it looks pretty awesome.  You’ve got designer and animator tools.  They are a wee pricey, but considering my Flash background, spending $279 on Sencha Designer and $199 on Sencha Animator doesn’t seem obscene.

What I can’t get past is having to spend $329 for a Javascript library license!  When I’m doing Flash/Flex development, I use the Flash Builder IDE for coding and sometimes Flash Professional if I’m doing animations or graphics.  And that’s cool.  I chose to buy into these tools.  I didn’t have to pay to use Actionscript 3 though.  My fellow developers who may not do Flash all the time can crack open any text editor and edit my code.  They can check it back into SVN and contribute to the project.  They can launch the Flex SDK command line and build my project.  None of this costs a dime.

If and when they get more invested in Flash/Flex, they might then want to buy Flash Builder or even IntelliJ for the advanced featureset including debugging, profiling, etc.

Not so with ExtJS.  I’m buying a license to use the code base.  Kind icky in my mind.  If I start a project in ExtJS/Sencha and I pay my $329 for the seat, but then I want some more help on the project occasionally, each developer will then need to pay out $329 just to use/edit the code no matter what tools they use.  If you are starting a major project, and plan the ExtJS cost into the budget, then great.  But if you’re a lone developer who wants to start something which blossoms into something bigger – the licensing can be a major roadblock.

Moreso, if I’m a consultant and I’m paid x dollars to develop a web application, I can easily choose and pay to use ExtJS.  After two months, I make a deliverable.  It might be the type of project where I do the major architecture and first phase, but then it gets shipped off internationally for maintenance mode or a lower cost second phase of the project.  Well, if you use ExtJS, you’ve just upped maintenance mode by $329 for every developer that needs to touch the project.  You’ve just cost your client lots of money.

This is why I discounted Sencha and ExtJS and moved on to exploring Dojo.  Dojo seems to offer MOST of what Sencha does.  They both have a rich set of components, offer lazy loading of scripts so that your massive enterprise application doesn’t load several hundred scripts (or a huge 2MB block of script) before the application starts up.  Both have a build system – Dojo’s runs on Rhino or Node, and is built on Closure or Shrinksafe.  ExtJS seems to be built off of a Yahoo builder.

In terms of scripting, both seem to nudge you in the direction of organizing your Javascript into classes which can be based on straight inheritance, or mixins.

Both seem to offer a visual tool for design.  Dojo’s Maqetta is free and can be used for jQuery, YUI, or Dojo.  I don’t see myself being very productive in it though – I can lay things out, but it wasn’t obvious to me if I could wire in data or do anything extensive.  Though I haven’t used Ext Designer, I have to imagine it’s a better product than Maqetta.  But then I seriously question how much I’d use a good tool for this anyway.  It’s like when everyone complains that design mode in Flex really sucks – but what if it didn’t? Would you actually use it, or just code everything?  I think we’d use it only like 5% of the time.  But this is all personal preference – ExtJS wins here, but only if you feel like you need a good design tool, which I don’t.

Dojo seems to offer one thing that ExtJS doesn’t though – and that’s declarative HTML markup.  This may be where my ExtJS ignorance comes in, so feel free to correct me if I’m wrong, but to mark up a component like you might do with Flex’s MXML, you write a JSON object describing the component or layout you’re introducing in ExtJS.  This is pretty cool – but with Dojo, you get to write REAL HTML.  I can tag existing divs or other elements as a Dojo component and they’ll act like Dojo components.  Yes, Dojo does offer templating, but you can choose which to use…or even to use both.

The worst part of Dojo?  They don’t have a MASSIVE marketing and tutorial push.  There is tons of ExtJS and Sencha material out there to learn from.  Yes, there is tons of Dojo material, but much of it is older and not up to date.  The material on the Dojo site is pretty technical and not very “quickstart-ish”.  What quickstart material they do have, don’t seem to be big picture enough to inform you what’s really going on.  I always had bad luck copying and pasting code from tutorials and having it work without spending hours debugging.  Most of the trouble with Dojo material is the switch to new loading routines that happened with the 1.7 release in December 2011.  I feel like when they release 2.0 sometime this year, we’ll have some better effort from the Dojo Foundation in terms of educating people on how to use the toolkit

All in all, Dojo and Sencha seem eerily similar from everything I read.  I feel so lucky that by learning Dojo, I’ll probably feel right at home in ExtJS as well.  For me it really comes down to the licensing that drives me to Dojo.  If that wasn’t an obstacle for me, there were more than a few times I’ve been frustrated by Dojo in the past couple weeks of learning it that I’d been open to abandoning ship if there was another choice.  I get the feeling though that there are similar frustrations with understanding ExtJS (helped in large part by their tutorials).

That’s why I’m team Dojo right now!  However, I’ll continue using jQuery for the smaller projects.  Dojo could easily replace jQuery, but for the smaller stuff when something minimal is all you need, there’s no sense in going against the grain and using something that not many people have experience with.

I’ll be posting more technical stuff on Dojo, but for now, this is how I got where I am!

iOS Video is Cranky!

Filed in development | ios | video Leave a comment

I’m close to wrapping up a decent sized iOS project, and my part was video playback.  Prior to this, I’ve done tons of work with Flash video.

I hate to be labeled biased, but I’ve never appreciated the level of detail put into the Flash API before working with both HTML5 and iOS.  Flash has tons of quality of service queries you can make, you have explicit control of bitrate on multibitrate streams, you have complete seek accuracy in streams.  Virtually anything you could ever want, you got it!

Compare that to the AVPlayerFramework API for iOS.  You can listen to status messages and put an observer on the current playhead time.  That’s pretty much it.  And those status messages come in the form of ready to “play”, “failed”, “played to the end”, “failed to play to the end” and “unknown”.

The lack of features actually isn’t too much of a problem for streaming playback.  Streaming content is handled like a champ by the framework.  A bad network connection might cause the stream to stutter, freeze, and stall – but as the connection gets better the video is recovered quite well automatically.

One of the complications presented by Apple’s guidelines is that an application that streams must provide an audio only low-bitrate stream to compliment the higher bitrate video/audio streams.  The AVPlayer framework does a great job doing what it needs to do switching the user to the best available stream.  Unfortunately, if bandwidth gets really bad, the audio only stream is a valid option – and iOS WILL switch to it.

It presents an interesting conundrum.  Video looks broken to the user, and especially your clients who are footing the bill.  I’d almost rather have the video stammer and stutter than to switch to this audio only bitrate – at least then, most tech savvy users would know that they are having network connectivity issues.

The other problem is the ability to seek to exact positions in a stream using the AVPlayer in anything less than iOS 5.  A stream is broken up into chunks.  Those chunks are transport segment (.ts) files.  Typically those chunks will be around 7-10 seconds each.  Turns out that if you want to seek to a specific second of your stream, it better lie at the beginning of a segment, otherwise your seek accuracy is (at worst) 7-10 seconds off.

Past that, streams are pretty decent, like I said.  What got frustrating though, was simple progressive video!

Progressive is fairly easy to play.  You load, play and go.  After loading, you need to wait for the item ready status, and then tell the content to play.  By nature, progressive loads welllll….progressively.  You can start playing back the video before the entire thing finishes loading.

The limited API of AVPlayer seems to present some problems here.  Your video is only “ready” once.  What happens if you are progressively playing, but suddenly your connection drops low, and you can’t quite finish playing the content because you’ve reached the end of whats been playing?  I’ll tell you what happens….your video pauses.  While paused, the rest of the video will finish loading.  Unfortunately, there is no status message to inform you that the video is ready to play again.  So there it sits.  Paused.

Drastic shortcomings call for stupid hacks.   Such as setting up a timer to fire off every few seconds and tell the content to play.  If the content is currently playing, the call to play will do nothing.  However, if it’s stalled and paused, we can keep the video moving along automatically.

Another shortcoming I ran across is an unfortunate reality with the AVQueuePlayer.  The AVQueuePlayer is like the AVPlayer, but you can playlist things.  I chose to use this type of player due to other requirements in my project.  For my work, I wasn’t really using it as a queue.  Instead, I’d simply replace the current item in the queue to play a new asset.  Unfortunately this method of doing things didn’t seem very reliable.  If an item failed in my queue, I could add further items and make them play, however I wouldn’t get any status events about the item.  That means I’d never get told when it was ready to play, when it completed, when it failed.  It was really a showstopper.  Sometime, even if the item didn’t fail to play, I’d see that subsequent items wouldn’t produce status changes.

I ended up having to destroy the player and starting fresh each time – oh well.  Even though I wasn’t using it as a queue before, now I REALLY wasn’t using it as a queue.

So there it is.  I got through it, but video was  a little cranky!

The ADSR Envelope with Audiolib.js

Filed in development | html5 | javascript | music | ui | web 6 Comments

So, let’s talk envelopes. First what they are, and what they can do to the quality of a sound.

Demo here: http://www.benfarrell.com/labs/examples/envelopes-12-17/, but read on for how it all works!

An envelope is a real simple concept actually. Take any signal, like a sound. Maybe that sound plays at a constant volume. When you apply an “envelope” to that sound, you are changing the volume of that sound while it’s played. It might go up and down, back up again, whatever.

How it goes up and down, and the speed at which the volume is changed is up to the details of the envelope used.

You could create an envelope that takes 8 hours to complete. Maybe you want to go to sleep with some music, and then wake up in the morning with music. If you know it takes you 30 minutes to fall asleep, you’ll start the music playing at a loud volume. Over the next 30 minutes, you envelope your sound from loud to quiet, to off. In the morning, 30 minutes before you wake up, the envelope makes the music go from off, to quiet, to loud again. It wakes you up!

While this 8 hours illustrates how an envelope works, it’s a bit different when talking musical tones.

It’s not that different, however. We’re still talking about volume over time, but we’re talking milliseconds instead of hours or even minutes or seconds.

The character or personality of a musical tone can be changed greatly by altering the envelope. While we talk about this in terms of 1/1000th of a second, you don’t really notice the volume changing as you listen to the tone. Your ear doesn’t necessarily detect that the volume is going up and down.

Instead, the sound just has a different tonal quality! A piano for example wouldn’t sound as sharp if it didn’t go from no sound to loud that quickly. An accordion though, has a longer time as it goes from quiet to loud. And that quality – the “attack” (amongst other factors) create the personality of the tone.

Let’s talk specifics now. ADSR.

That’s Attack, Decay, Sustain, Release. The ADSR envelope is just one type of envelope, but it’s a popular one that’s been used in electronic music for decades.

  • Attack is the period of time after the initial release, it’s typically the loudest part of the sound
  • Decay is the phase while you’re going from the attack to the sustain – you’re “decaying”  the volume from this sharp initial phase to the normal volume phase
  • Sustain is the normal phase of the sound.  It is typically less volume than the attack, and go on for an indefinite period of time, or for a specific amount of time
  • Release is the draw down from the sustain period to no sound.  A fade out

the attack, decay, sustain, and release phases

I’ve talked about Audiolib.js in previous posts.  Audiolib is the Javascript library that enables you to make these dynamic sounds in Chrome and Firefox.

Audio programming isn’t easy though!  So while Audiolib helps out in awesome ways, it doesn’t have concepts of notes and music theory.  You have to tell it what frequencies to play, and if playing a chord, which individual frequencies make up the chord – which I explored and created my own helpers for.

The ADSR envelope is another example of something that Audiolib.js provides, however, it doesn’t provide any obvious usage for it.

There’s actually a VERY good reason for this.  While, we’re talking about envelopes on musical tones, the 8 hour sleepy-time envelope is another good usage example.  And that’s restricting envelopes to the volume of a sound.  There are tons more examples in audio synthesis that envelopes can be applied.  Like effects – you can apply a distortion effect to a sound (like a rock guitar).  But you can envelope the amount of distortion which is applied to the guitar.  This has nothing to do with volume, and everything to do with just how much of something is applied to something else.

So, I’d like to create a usage of our ADSR envelope that is limited to producing a musical tone – especially in the example of producing live sound by using a trigger (here it will be your computer/laptop keyboard).

Let’s start with our previous example where we extend the Audiolib.js Oscillator via a plugin.  We extended it to simply take a musical notation, like an “A” and set the correct frequency:

audioLib.generators('Note', function (sampleRate, notation, octave){
// extend Oscillator
for ( var prop in audioLib.generators.Oscillator.prototype) {
this[prop] = audioLib.generators.Oscillator.prototype[prop];
}
// do constructor routine for Note and Oscillator
var that = this;
 
// are we defining the octave separately? If so add it
if (octave) {
notation += octave;
}
that.frequency = Note.getFrequencyForNotation(notation);
that.waveTable = new Float32Array(1);
that.sampleRate = sampleRate;
that.waveShapes = that.waveShapes.slice(0);
}, {});

So let’s figure out how to work in an ADSR envelope. The usage for the Audiolib.js version is like so:

myEnvelope = audioLib.ADSREnvelope(sampleRate, attack, decay, sustain, release, sustainTime, releaseTime);

The parameters work like so:

  1. Sample Rate:  The sample rate of the audio – I won’t go into it here, as it’s a basic setting for audiolib
  2. attack – the amount of time (in milliseconds) that the attack phase takes to complete
  3. decay – the amount of time (in milliseconds) that the decay phase takes to complete
  4. sustain – the level of volume during the sustain phase (from 0 to 1)  - the default is 1
  5. release – the amount of time it takes for the release phase to complete (in milliseconds)
  6. sustainTime – the amount of time it takes for the sustain phase to complete (in milliseconds).  This param is pretty important though, because if you pass in null, the sustain period is indefinite.  Unless you call into the envelope with a trigger, it will continue being in the sustain phase forever
  7. releaseTime – the amount of time between the release phase and the envelope looping around to the attack phase again

The envelope has 6 states of being (0-indexed inside the code):

  1. Attack Phase
  2. Decay Phase
  3. Sustain Phase
  4. Release Phase
  5. Timed Sustain Phase
  6. Timed Release Phase

To kick off our envelope, you trigger it:

myEnvelope.triggerGate(true);

Now we can start using our envelope.  The usage is a little weird to me, as the Audiolib.js library treats it like a “generator” which seems a bit complicated for what it does.  I just want a stream of numbers, but OK I’ll bite.  I’ll use it with the byte arrays and whatnot, as if it’s an Oscillator.

var buffer = new Float32Array(1);
myEnvelope.append(buffer, 1);

So, I’m just pulling one value at a time from the envelope, and putting it into my “buffer”.  But my buffer only has one value in it at any time.  Like I said, I feel like I’m being forced into using it in more complicated of a way than I need!  Maybe there’s something I’m missing.

Now, every time, I get create an audio data point in my sound, I can multiply the data point by my envelope.  Thus my envelope is applied!

this[this.waveShape]() * buffer[0];

To do this, I overrode the “getMix” function in the Audiolib Oscillator.  But I needed to do other things too.

Since I trigger the envelope with triggerGate, it will cycle through the attack and release to the sustain phase as the envelope is used, automatically.

It gets complicated at the release phase though.  After your computer/laptop keyboard is released, we need to enter the release phase.  But we’re still grabbing sound, because the release phase still produces sound as it fades.  So our Oscillator needs to track that it’s in the release phase (it knows by keeping track of the envelope.state, which is 3 or 5 here for release or timed release).

Then finally when it gets back to state 0, or the cycle begins again, we mark this note as “released”, so our buffer knows that it doesn’t need to pull from it anymore.  We have to be very careful of note pulling from more notes than we need, cause all this music stuff is hard work, and too many notes slows down your CPU and breaks the audio processing.

The above is if the sustain phase goes on as long as you hold the key!  What if it’s a timed sustain – then we need the logic in there to release the key when the envelope is done, rather than when our user releases the key.

Here’s our final Note.js code.  And here’s a controller for keeping track of keys being pressed.

It all comes together in my (Chrome only) demo:

http://www.benfarrell.com/labs/examples/envelopes-12-17/

The demo starts out by not using an envelope at all.  You’ll hear some clicky-ness when you press and release a key.  That’s because you’re hearing the transition between no sound and the abrupt start in the phase of the waveform.  It’s EXACTLY one of the reasons why envelopes are useful – to ease these transitions in and out.

When you turn on the envelope, you can start adjusting parameters to see how the different properties of attack, decay, sustain, and release affect the overall personality of the tone.

Making an Audiolib.js Plugin

Filed in development | html5 | javascript | music | ui | web Leave a comment

I just started checking out Audiolib.js this weekend.  Audiolib is a Javascript project to help you synthesize sounds and tones in JS.

Just recently, Google Chrome added the Web Audio API, while Firefox added the Audio Data API.  Both let you get low level with sound – you can add bytes to an audio buffer and manufacture sound in realtime.

The library is bundled with “sink.js” which handles the inconsistencies in the audio API between Firefox and Chrome to create a common API.  Once this is abstracted away, we can make some audio.

I’ve done the nitty gritty of writing bytes to the buffer in Flash, and from my limited playing Audiolib does a great job with this, and I’m ecstatic I don’t have to rewrite my Flash stuff!

Audiolib provides “generators” for you to work with.  A “generator” is something that makes a sound, and defines a common API for anything that makes a noise to write that sound to the audio buffer.

In the generators namespace/package, we have an Oscillator, White/Pink/Brown Noise, and a Sampler.  White noise is cool and all, but I jumped right to the Oscillator to make a real tone.  The Oscillator takes a sample rate and a frequency.

You can define it thusly:

dev = audioLib.AudioDevice(audioCallback /* callback for the buffer fills */, 2 /* channelCount */);
osc = audioLib.Oscillator(dev.sampleRate /* sampleRate */, 440 /* frequency */);

So, first we defined the device to use – we told it what to use for the audio callback, and how many channels there are (we have 2 channels…left and right).

The audio callback is a pretty standard thing in the world of audio. When the sound card is starting to run out of audio to play, it signals Javascript and says “Hey I need more audio! Fill me up with some bytes”. With our “audioCallback” function, we say “No problem sound card! I got your back! When you run low, please call our audio callback method – this will fill your audio buffer up”

Here’s an example of the audio callback:

function audioCallback(buffer, channelCount){
  osc.append(buffer, channelCount);
}

All that happens here, is that the buffer and channel count gets passed into the method, and we tell out Oscillator what this is, and this Oscillator generates the appropriate bytes and send them to the buffer.

But what is that generator…the Oscillator? Well, it creates a sound at a certain frequency. We pass in the frequency as we instantiate this “osc” object. When the audioCallback fires, it pulls this frequency from the osc object and plays a specific tone!

This is awesome! All the hard work is done for us – but one of the first things I wanted to tackle here was to make it easier for musicians to understand.

See, casual musicians don’t know that a middle “A” on a piano oscillates at 440hz – they just know that they hit a middle “A” to play the tone. I want something that makes sense for casual musicians, so my first small task with audiolib is to override Oscillator to take a notation vs a frequency.

Audiolib provides a plugin spec, but it tripped me up a little to understand how a “Generator” worked. See, they have a js/generation folder which contains the Oscillator. It’s all quite readable and self-documented.

However, the “append” method was not found in the Oscillator class at all! I was looking EVERYWHERE for it!

Eventually I found it in the “wrapper-end.js” script that’s outside of all the folders.

Basically, you create a generator like Oscillator, and you write it to the audiolib.generators namespace. By virtue of being in this namespace, the “wrapper-end” script comes along to wrap things up. It takes all the things in the audiolib.generators namespace and adds the generator base functions. Basically it makes all the generators extend the generator base class after the fact.

Kinda confusing and sneaky if you ask me! Oh well.

Regardless, the plugins are well documented, so I copied the sample generator plugin:

audioLib.generators('SemiClock', function (sampleRate){
	this.sampleRate = sampleRate;
}, {
	prevSample: 0.0,
	generate: function(sample){
		this.phase = + !this.phase;
	},
	getMix: function(){
		return this.phase;
	},
	phase: 0
});

Cool, so we’re naming a generator in the generator namespace, and defining some required methods, like “generate” and “getMix”.

Well, all I want to do is make a copy of all the objects in Oscillator and add a function and initialization routine to accept a musical notation and instantiate an oscillator with the correct frequency.

So here’s my take:

audioLib.generators('Note', function (sampleRate, notation, octave){
    // extend Oscillator
    for ( var prop in audioLib.generators.Oscillator.prototype) {
        this[prop] = audioLib.generators.Oscillator.prototype[prop];
    }
 
    // do constructor routine for Note and Oscillator
	var	self = this;
    self.octave = isNaN(octave) ? 4 : octave;
    self.setNotation(notation);
	self.waveTable	= new Float32Array(1);
	self.sampleRate = sampleRate;
	self.waveShapes	= self.waveShapes.slice(0);
}, {
    /* incremental tones as sharp notation */
    sharpNotations: ["A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"],
 
    /* incremental tones as flat notation */
    flatNotations: ["A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"],
 
    /**
     * notation setter
     * @param notation (octave is optional)
     */
    setNotation: function(nt) {
        this.notation = nt;
 
        // does notation include the octave?
        if ( !isNaN( parseInt(nt.charAt(nt.length -1)) )) {
            this.octave = parseInt(nt.charAt(nt.length -1));
            this.notation = nt.substr(0, nt.length-2);
        }
        this.frequency = this._getFrequencyForNotation(this.notation);
    },
 
    /**
     * turn a notation into a frequency
     * @param notation
     * @return frequency
     */
    _getFrequencyForNotation: function(nt) {
        var freq;
        var indx = this.sharpNotations.indexOf(nt);
 
        if (indx == -1) {
            indx = this.flatNotations.indexOf(nt);
        }
 
        if (indx != -1) {
            indx += (this.octave-4) * this.sharpNotations.length;
            freq = 440 * (Math.pow(2, indx/12));
        }
        return freq;
    }
});

Basically what I did here is extended the Oscillator class. I looped through all the properties of the Oscillator.prototype object and copying it onto the new class.

I then, went in to the Oscillator generator and copied the small initialization routine.

Then I injected my own methods! I replaced the frequency setting with a method to lookup the index of the musical notation in my preset arrays of notations. I also parsed out the octave (if it existed).

In the end, I have a “Note” class which is exactly the same as the Oscillator class – however, instead of passing in the frequency (ie 440hz), you pass in “A”, or “A4″ for the 4th octave.

To change the notation of the oscillator/note, simply call the setNotation again!

I’m definitely looking forward to exploring Audiolib.js more. It has a few concepts that I hadn’t gotten around to implementing in my own Flash framework yet, so I’m excited to see how it’s done.
 

Javascript: We don’t need no stinkin Blueprints

Filed in development | javascript Leave a comment

So, at this point I feel like I’m a competent JS developer. Not pro, just competent. Since I can’t just let things lie there, I’m reading “Secrets of the Javascript Ninja” and trying to get a handle on what Javascript, and even a functional language mean as you work with them.

One of the biggest complaints I have so far is the openness that the language allows. It sounds stupid I know, because why wouldn’t it be a good thing to allow you to do anything you want?

Well, I like to learn by doing. After I “do”, and finish one or two projects, I start to question the underlying ways of doing things, and I learn.

I’m not the type to read about the building blocks for several weeks, and say “Hmmmmm…..I understand these building blocks, now is the time to code”.

Nope! I just plow through – it’s OK I don’t understand the fundamentals, if I’m following a best practice, then I can trust that the best practice is correct and learn as I go.

Coming from Actionscript, I obviously want to be more object oriented. I’ve finally grasped that there’s no good way to emulate this without something like John Resig’s Class construct: http://ejohn.org/blog/simple-javascript-inheritance.

That’s fine, but it took me a while to accept this. After all, Javascript is pretty much object-oriented, why is it such a chore to make classes and extend them in an OO fashion?

I had to take a big step back to think about what languages like Java and AS3 do to make them what they are. The big difference, I found is NOT that Javascript lacks OO features, but that it lacks blueprints/definitions.

Blueprints are one of those things that have always been there for me, but I always took them for granted. Also known as definitions, they sit in around waiting to be spun up as an object in memory.

These blueprints basically serve as a model for how, once you instantiate the object, what it will look like and how it will function after you call new MyBlueprint().

You can let a blueprint know what properties and methods it’s supposed to have. You can also say that BlueprintX extends BlueprintY (inheritance), and it implements the same type of methods as IBlueprint (an interface).

It’s all very convenient, and gives a good model of how to structure your code. It also sits in the background, lying in wait to be spun up. I’m assuming that it doesn’t cost anything at runtime besides the memory to store the text of the class.

Anyway, it seems that Javascript doesn’t have the notion of a blueprint! The only thing close to a blueprint is the base Object. Apparently, the only blueprint in Javscript is stored in the Object.prototype property. You can’t define any thing extra before your browser instantiates! Oh well. It’s just something to accept and move on, but it really was a major mental block for me in how the language functions.

Instead, when you need to create a blueprint like thing, you create whatever you need at runtime. Javascript allows you to create a base object, set whatever properties you want on it, and then manually clone it to other types of things.

So you can certainly create something that you’d like to use as a blueprint, but you are instantiating this model at runtime as a normal everyday object. It resides in memory like any other object. It’s just that YOU, the programmer decides to use it as a blueprint – so you make the decision to clone it, extend it, mix it with other inheritances, etc. All manually.

No big deal, but like I said, the lack of a formal blueprint model was a real head scratcher for me, and it made me think about what I was missing and was taking for granted in every other language I’ve ever used! My initial knee jerk reaction was to say “Javascript isn’t OOP”, but that’s not true – it just doesn’t need any stinkin blueprints.

Hello from NCDevCon! My 2011 Presentations

Filed in development | flash | flash/flex | flex | html5 | ios | music | ui | video | web Leave a comment

Hello from NCDevCon.  If you were able to attend my presentations, thanks!

I’ve gone ahead and written them up as blog posts for you if you’d like to revisit what I talked about.

 HTML5 vs Flash Video: Choose Wisely (slides)

Live Instrumentation in Flash (slides)

Live Instrumentation in Flash Part 6 – Some Demos

Filed in development | flash/flex | flex | music | web Leave a comment

Demos

HTML5 vs Flash Video: Choose Wisely Part 10 – Other Options

Filed in development | flash | flash/flex | flex | html5 | ios | javascript | ui | video | web Leave a comment

Lets face it, Apple really stuck us in a bad situation.  While HTML5 is really slick on the desktop (in supported browser with supported file types), its pretty clunky on iOS.  And Flash is ALSO really slick on the desktop, but doesn’t work at all on iOS.

So what we are left with are 2 things that work really well on the desktop, but no common thing that works well on Android, iOS, and the desktop.

What can we do?

Native iOS

Simply the best option on iOS now is to sign up for a developer’s license and make an app.  iOS offers two different video player frameworks MPMoviePlayer and AVPlayer.  MPMoviePlayer is the simplest to get started with, and offers you playback through the Quicktime UI.  AVPlayer is harder to get started with and you are forced to create your own UI, but you have more control over video playback.

AIR for Mobile

What may be the best solution is to build a Flash player with HLS streams on iOS and normal HTTP or RTMP streams on Android or the desktop.  While it’s true that Flash isn’t supported on iOS, Flash Builder 4.5 can compile your existing project out to iOS and Android applications.  All Flash video is supported in AIR, Mobile AIR and the web Flash player – except for iOS.  So you’ll need the two different streams.

Corona and other 3rd Party Packagers

Corona seems to be a very popular way to create cross platform mobile apps these days.  There are other packagers as well like Titanium, Appcelerator and more.  Last I looked they don’t handle video, or don’t handle video very well.  Probably the best is Corona which does allow video to play, but it needs to launch the video in a modal window or fullscreen, and you have little control over it. As cool as these solutions are, I don’t believe that they handle video all that well.

HTML5 vs Flash Video: Choose Wisely Part 8 – Advertising and Reporting

Filed in development | flash | flash/flex | flex | html5 | ios | javascript | ui | video | web Leave a comment

Before we conclude this series, I should mention something nobody likes – but they are an absolute necessity if content producers are going to put their video online in the first place.

Those things are ads and reporting.

Content owners want to monetize their video, and be able to track many aspects of it’s usage to make better decisions about video you’re watching.

With Hulu, Netflix, and many networks putting first run television online it seems that web video is gaining on what we watch on cable TV, and we may see a day soon when the web is significant enough to eat into cable tv’s revenue model such that we’ll networks and content producers who want to thrive can’t afford to just be on one or the other.

As ad revenue from cable tv and network broadcasts are shifted, owners will want to make sure this money is JUST shifted and not lessened.  So even today, folks are experimenting with longer ad breaks to see if they can get away with the same video experience you see on TV.

To accomplish this, we need some good 3rd party libraries from ad companies and reporting companies, as well as decent support on the actual device, browser, or plugin to facilitate these advanced needs.  If we can’t come up with creative solutions to accommodate ads and reporting, companies will simply not come – and this can make or break a platform’s usefulness for serving video.

3rd Party Library maturity

I’ve been working with Flash video extensively for a few years now, and in that time I’ve seen 3rd party frameworks and libraries delivered to us from various ad and reporting companies (many revisions in fact).  Flash seems to have a lock on maturity of 3rd party libraries for handling these things.  Flash has almost maniacal support for every aspect of playing video – something you won’t see from HTML5, or even iOS (from what I’ve seen so far).  In truth, this is why Flash is difficult to work with for video newcomers.  But, at the same time it offers extreme control to allow almost anything we need.  We can offer midrolls, prerolls, postrolls, companions, overlays and more.  We can also track video buffering events, stream transitions, and many more minute details.

HTML5 video, on the other hand doesn’t have this level of control – especially in iOS given the playback obstacles we’ve discussed.  Given this – many 3rd party libraries are still figuring out how to offer the same level of ads and reporting we can obtain from Flash players.

One company I work with just recently started offering midroll ads, where before their Javascript/HTML5 video solution wasn’t mature enough to do this.  They seem to be coming along just fine, but won’t be caught up to Flash anytime soon!  See part 6 for my experiences working with mid roll ads.

Advertising with MP4 – At Least that’s Easy!

I’ve talked about iOS streaming for long-form content.  It uses Apple’s HLS, and is pretty much incompatible with Flash or Silverlight.  As a result, content owners will need to completely re-encode their streams for Apple devices – that is IF they want it to be streaming.

Many advertisers these days, however, will serve up their ad creatives as mp4 files encoded with h264.  This works on Flash, and it ALSO works on iOS, Chrome, and IE.  This means that if these advertisers wanted to use their same ads on iOS, they’re free to do so without have to re-encode the files!

Companion Ads and Banners

The same can’t be said for companion ads, however.  Companion ads are static or animated images that you see outside the video player area (usually in another div on the page).  The problem is that these ads, in my experience, aren’t static images and usually animated Flash.  This means that advertisers and content producers need to work together to create new companion creatives and serve them up appropriately for Flash or iOS.

TOP