Creating a play/pause toggle using the Spacebar in Flex

March 24th, 2008 . by polyGeek

I’m creating a Flex based videoPlayer/slideShow viewer for a client. One small usability feature that I wanted to add is making the Spacebar act as a play/pause toggle.

Click on any button or
the stage to give the SWF focus
view source code

It’s not as straight forward as one might think. First off if you create a Flex application then which ever component has focus receives the keyboard input. Which is really cool unless you don’t want it to do that. And this is the first occasion I’ve had for using applicationComplete() before. Because you have to have access to the application stage in order to set up the keyboard event and that isn’t available on creationComplete() - as noted here at the Flex cookbook.

Here’s the gist of the code:
private function appInit():void {
stage.addEventListener( KeyboardEvent.KEY_DOWN, keyPressHandler );
}
private function keyPressHandler( e:KeyboardEvent ):void {
// if the spaceBar is pressed then toggle video play/pause
if( e.charCode == 32 ) {
if( this.focusManager.getFocus() != toggleBtn ) {
this.focusManager.setFocus( toggleBtn );
// whatever happens when you click on the button you place here
// it's best to have a 'clickHandler' that calls another method
toggleBtnHandler();
}
}
}


Why Actionscript

March 21st, 2008 . by polyGeek

Here’s my Why Actionscript video for the 30onair series. ( You can see the youTube version here but it’s compressed to hell. )

The effect was created - serendipitously - by using a combination of bitmapData effects. The gist is to take two webCam video windows and place one on top of the other. Offsetting the top one by a few pixels x/y and giving it a blend mode of ‘difference’. Then create a BitmapData object that draws the content of the sprite holding both windows. Now use threshold and mix in a few blur filters and merging and you get the above - in realtime.

This is the core of the code that creates the effect:
private function onTic( e:TimerEvent ):void {
bmpDataSource.draw( camsHolder ); // this is the bitmap data inside the camsHolder
// applying a threshold to the bitmap data
bmpDataSource.threshold(bmpDataSource, rect, pt, ">", 0xFFbdbdbd, 0xFFFF0000, 0xFFFFFFFF, true );
// you can change the settings and order that these are applied to get
// lots of different effects. Some are really cool. A lot produce black screens
// you never know until you try. :-)
bmpDataSource.applyFilter( bmpDataSource, rect, pt, blurEffect );
bmpDataDisplay.copyPixels( bmpDataSource, rect, pt );
bmpDataDisplay.applyFilter( bmpDataDisplay, rect, pt, blurEffect );
bmpDataDisplay.merge( bmpDataSource, rect, pt, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF );
}

Here’s the full code. ( Something’s broken in the published setting. You have to use the leftNav to load the code views. )

And I also found what, I think, is a pretty good AIR theme song.

If you have a webcam you can see it in live action here.

Did you see the Master Chief’s helmet in there?


Example of getColorBoundsRect()

March 19th, 2008 . by polyGeek

Here’s what the Actionscript 3 docs have to say about getColorBoundsRect()

Determines a rectangular region that either fully encloses all pixels of a specified color within the bitmap image (if the findColor parameter is set to true) or fully encloses all pixels that do not include the specified color (if the findColor parameter is set to false).

That makes a lot more since if you see it in action. Click on the SWF below to see how the rectangle is drawn. In this case getColorBoundsRect() is returning a rectangle that encloses the selected color under the mouse pointer.



[ view source ]

Here’s the meat and potatoes of the code:

private function clickHandler( e:MouseEvent ):void {
var color:uint = bmpData.getPixel32( mouseX, mouseY );
var rect:Rectangle = bmpData.getColorBoundsRect( 0xFFFFFFFF, color );
outline.graphics.clear();
outline.graphics.lineStyle( 1, 0x000000, 1 );
outline.graphics.drawRect( rect.x, rect.y, rect.width, rect.height );
}

You can read more about it on the Actionscript 3 docs. Or in the Actionscript 3 Bible, page 637.


A fountain of imagination and knowledge has passed

March 19th, 2008 . by polyGeek

[ view source ]

Author C. Clark has passed. He was probably . . . no, he was the most influential man during my adolescence and early adulthood. He’s the main reason I began college as an astronomy major at the University of Arizona - later to get sidetracked into mathematics, history, philosophy, etc.

I read nearly all of his books, both science fiction and science. Along with the 2001 and 2010 Odysseys I love his books Songs of Distant Earth, Childhoods End, and Fountains of Paradise. And it boggles my mind that A Fall of Moondust hasn’t been made into a movie yet.

One of my favorite quotes comes in the acknowledgment of one of his books, “In accordance to the Clark/Asimov treaty the second best science writer dedicates this book to the second best science fiction writer.”

I read his bio a few years ago and it really stuck me that he wrote the screenplay for 2001 from Sri Lanka. He would fax the changes to Stanly Kubrik, they would talk on the phone and then he would go back to editing again. And this is in the late 60s that he was doing this. Sending a fax on a daily basis from Sri Lanka, in the 60s. That’s bleeding edge!

In watching 2010 the sceen that really sticks out for me is where Floyd is talking to Bowman as Bowman transforms through various ages. The old man version of Bowman says, “You see, it’s all very clear to me now. The whole thing. It’s wonderful.”

I hope AC is with the Star Child, and it’s wonderful.

A bit about the code
There’s not much to see in the code of my tribute. It’s a poor rendition of the most popular screen saver of all time. ( I wonder what AC Clark’s screen saver was. ) It’s just something I knocked together while watching 2010 again tonight. ( The movie still holds up very well.) I used the TweenLite tweening engine for the first time. I played around with a fullScreen version but I can’t get the Kimili plugin to accept the allowfullscreen attrubute. ( Yes, I have the most recent version of Kimili. )

Oh, don’t hang out on this page too long. There is a memory leak in the FullStars.swf. When a tween completes it calls to a callback function and that callback simply creates another star in a random position and then tweens it to the center. I looked through the TweenLite code and it seems to try and clean up a reference when a tween completes. But something isn’t going right. It’s probably something I overlooked. Anyway, if you’re computer is slowing down you might want to browse on from this page. :-)


Getting Booleans from E4X

March 13th, 2008 . by polyGeek

I got stuck on a problem the other day using E4X. I was simply trying to get a Boolean value out of an attribute. It seemed to me that I could simply say:

setAutoPlayVideo( p.@autoPlayVideo );

Where autoPlayVideo is an attribute with a value of either “true” or “false”.

I expected E4X to type the variables I was using because I hadn’t needed to cast any of the attributes that were Strings or Numbers. Those all worked fine. After debugging a bit I discovered that each attribute was actually typed as XML. I’m a bit spoiled by my PXP2 class which automatically types values as Number, Boolean or String.

In the case of E4X and Booleans it was simple enough to fix once I understood what was going on. This does the trick:

var b:Boolean = ( p.@autoPlayVideo == "true" ) ? true : false;
setAutoPlayVideo( b );

Or if you’re not used to the ternary operator

var b:Boolean
if( p.@autoPlayVideo == "true ) {
b = true;
} else {
b = false
}
setAutoPlayVideo( b );


SpringyTiles : break an image into tiles that spring to place

March 12th, 2008 . by polyGeek

I’ve been playing around with Bitmaps/BitmapData and came up with this. The main .as class loads an external image and then uses a Tiles.as class to break the image into rows/columns and then randomly position the tiles so that they can spring back into position.

The meat and potatoes of the work is done with the BitmapData.copyPixels() method:

bmpData.copyPixels( imgData, new Rectangle( c * w, r * h, w, h ), new Point() );

Where c and r stand for the current column/row.

The spring code is right out of Keith Peter’s Making Things Move for AS3 book, chapter 8, page 202. Thanks Kieth.

There’s a handful of features that I’d like to add to this just for funzies. If you think of something interesting tweak to add just comment and I’ll see about it.

And of course the source is well documented, mostly.

Note to FlexBuilder programmers: thanks for applying my code coloring preferences. But you missed the body:background-color. I had to manually add that. Otherwise it’s unreadable.


Using ExternalInterface on a local machine

March 11th, 2008 . by polyGeek

A reader emailed with a problem he’s having with the ExternalInterface. It seems that his code works fine when the page is hosted on a server but doesn’t work sometimes when accessed directly on the PC. ( Meaning opening the file locally in the browser with a C://path/filename. )

I seem to recall some issues that I had in the past but I haven’t worked with the ExternalInterface in over a year.

The error he gets is: Object or property is not supported.

The reader who asked the question said that he found no mention online nor in the documentation about this. Anyone out there know what’s the what?


Publishing Flex projects with Flash keyboard shortcuts

March 10th, 2008 . by polyGeek

I can’t believe I didn’t think of this earlier. It’s simple to change the keyboard shortcuts in FlexBuilder so I changed the “Run” keyboard shortcut from Shift + F11 to Ctrl +Numpad_Enter. That’s what I was used to in the Flash IDE. And I changed Debug to Ctrl + Enter. It’s a small change but makes FlexBuilder seem a little more familiar.

Go: Window -> Preferences… Expand  General and select Keys. Then just  scroll down to Run. ( To get there faster type run into the “type filter text” field and then scroll. )

FlexBuilder keyboard shortcuts

And it’s not a bad idea to scroll through the, rather long, list of actions that can have keyboard shortcuts. There’s a bunch of things in there I didn’t even know FlexBuilder could do.


Flex Library Projects - the equivalent of the Flash IDE’s Global Classes

March 6th, 2008 . by polyGeek

In the Flash authoring tool ( IDE ) there’s a preference called your Global Class Path. You can set that path(s) as a preference in the application so that every single FLA that you create will have access to those classes.

I’ve been trying to figure out how to do the same thing in FlexBuilder for ages. If you came to FlexBuilder as a Java developer then this should be old news to you. But for someone new to FlexBuilder it’s a pain trying to figure out even the basics of Eclipse. The books on Flex mostly gloss over the inner workings of FlexBuilder.

In this video tutorial I’ll cover how to build a Flex Library Project - the equivalent of your Global Class Path in the Flash IDE. You can then add your Actionscript and MXML classes to that project and have access to them throughout your workspace without doing an import and duplicating your files.

[ Download Flex Builder 3 | [ Download FLV | Download _comPolygeek.swc ]

Here’s the Adobe documentation on Creating Flex component library files.

Ryan, Sim, I miss you guys! :-)

Addendum: Ted Patrick pointed out that you can drop a SWC into the “libs” folder of your Flex3 projects.