Posts filed under 'flash'

HOWTO Create a Facebook App using FlexBuilder

So for a couple of weeks, I’ve been messing around w/ building a simple using Facebook. I decided to use the new ActionScript 3 API created by Adobe and Facebook. I wanted to do a little tutorial because some of this information is hard to understand since most of the API has definitions like, ” “.

In this tutorial I will show you how to login to Facebook, retrieve your friends list and populate a TileList with their pictures. Ok, let’s get started.

Step 1: Get an account (If you don’t have a Facebook account, that would be wierd. People in nursing homes have them).

Step 2: Create a developer App (link to directions by Adobe)

Step 3: Set up a Flex Project (link again to Adobe. Stop on step 7)

Step 4: in Design view drop in two Buttons, a Text, ComboBox and TileList components.

Step 5: enter the text into the labels of the buttons as they are in the picture below.

basedesignview

Then the TileList

Step 6: Now to make changes to the TileList we need click on the TileList and look at Flex Properties in the Flex Development View. In the Flex Properties set Column Count to 4 (ignore the row count).

Ok now we have the visuals let’s get to my favorite, coding.

Step 7: We are going to make ids for all componets so we can reference them in the code. The first Button name “loginbutton”, the label name “title”, the combobox name “sortBox”. See below to check your code.

<mx:Button id="loginbutton"
 
label="Click after you log into Facebook"
 
x="10" y="10"/>
 
<mx:Label id="title"
 
text="Hello you" x="10" y="40"/>
 
<mx:Button label="get Friends"
 
x="10" y="66"/>
 
<mx:ComboBox id="sortBox" x="10" y="96"/>
 
<mx:TileList id="friendsList" columnCount="4" width="400" height="400"
 
x="10" y="126">
 
</mx:TileList>

Step 8: we are going to put in all of the imports and variables.

<mx:Script>
 
<![CDATA[
 
]]>
 
</mx:Script>

Wrap this in side of the Script block.

import com.facebook.commands.notifications.SendEmail;
 
import com.facebook.commands.notifications.SendNotification;
 
import mx.utils.StringUtil;
 
import com.facebook.data.FacebookErrorCodes;
 
import mx.controls.Alert;
 
import mx.events.ListEvent;
 
import mx.events.ItemClickEvent;
 
import mx.collections.Sort;
 
import mx.collections.SortField;
 
import com.facebook.data.users.FacebookUserCollection;
 
import mx.collections.ArrayCollection;
 
import mx.controls.List;
 
import com.facebook.data.friends.GetFriendsData;
 
import com.facebook.commands.friends.GetFriends;
 
import com.facebook.data.friends.FriendsData;
 
import com.facebook.data.friends.FriendsCollection;
 
import com.facebook.data.users.GetInfoData;
 
import com.facebook.data.users.FacebookUser;
 
import com.facebook.events.FacebookEvent;
 
import com.facebook.Facebook;
 
import com.facebook.utils.FacebookSessionUtil
 
import com.facebook.net.FacebookCall;
 
import com.facebook.commands.users.GetInfo;
 
import com.facebook.data.users.GetInfoFieldValues;
 
import com.facebook.data.users.FriendsGetData;
 
[Bindable]
private var _friendsCollection:ArrayCollection;
 
private var fbook:Facebook;
 
private var session:FacebookSessionUtil;
 
private var user:FacebookUser;
 
private var sortTypes:Object;
 
private var answerPerson:String;
 
private var answer:String;
 
private var alert:Alert;
 
private var _apiKey:String = "{YOUR APIKEY}";
 
private var _secret:String = "{YOUR SECRET CODE}";
 
private var _friendSearched:String;
private var quizFriendsCollection:ArrayCollection = new ArrayCollection();
[Bindable]
public var sorts:ArrayCollection = new ArrayCollection([{label: "A-Z", data: "last_name"}, {label: "Z-A", data: "last_name"}]);

Step 9: We are going to create an init function to be called on applicationComplete. THis will go out, log you in and create a session.

private function init():void
{
fbook=new Facebook();
session=new FacebookSessionUtil(_apiKey, _secret, stage.loaderInfo);
fbook=session.facebook;
<div><code>session.login();
session.addEventListener(FacebookEvent.CONNECT, onConnect);
}</code></div>

Don’t forget to add an applicationComplete to your Application Tag.

Step 10: we are going to create the response to us connecting to Facebook. It will return our id which we will make another call to get all of our info for our account.

private function onConfirmLogin():void
{
 
this.removeChild(loginbutton);
 
session.validateLogin();
}

//also change this button

&lt;mx:Button id="loginbutton"
 
label="Click after you log into Facebook"
 
click="onConfirmLogin()" x="10" y="10"/&gt;
 
private function onConnect(e:FacebookEvent):void
{
var call:FacebookCall=fbook.post(new GetInfo([fbook.uid], [GetInfoFieldValues.ALL_VALUES]));
call.addEventListener(FacebookEvent.COMPLETE, onGetInfo);
}

This should only return one result. The title text we named will display the account first and last name

private function onGetInfo(e:FacebookEvent):void
 
{
 
for (var i:int=0; i &lt; (e.data as GetInfoData).userCollection.length; i++)
 
{
 
user=(e.data as GetInfoData).userCollection.getItemAt(i) as FacebookUser;
 
title.text="Hello " + user.first_name + " " + user.last_name;
 
}
 
}

Step 10:Let’s get some friends.

//This gives just the ids of your friends
 
private function getFriends():void
 
{
 
var call:FacebookCall=fbook.post(new GetFriends());
 
call.addEventListener(FacebookEvent.COMPLETE, onGetFriends);
 
}
 
private function onGetFriends(evt:FacebookEvent):void
 
{
 
if(evt.error)
 
{
 
alert = Alert.show(evt.error.errorMsg, "Error: " + evt.error.errorCode);
 
return;
 
}
 
var friends:FacebookUserCollection=(evt.data as GetFriendsData).friends;
 
var uids:Array=[];
 
var userFriend:FacebookUser;
 
for (var i:int=0; i &lt; friends.source.length; i++)
 
{
 
userFriend=friends.getItemAt(i) as FacebookUser;
 
uids.push(userFriend.uid);
 
}
 
//get all the info of a friends
 
var call:FacebookCall=fbook.post(new GetInfo(uids, [GetInfoFieldValues.ALL_VALUES]));
 
call.addEventListener(FacebookEvent.COMPLETE, onHandleFriends);
}

Don’t forget to add the getFriends function to the click handler of the Button labeled “get Friends”

private function onHandleFriends(e:FacebookEvent):void
 
{
 
if(e.error)
 
{
 
var alert:Alert = Alert.show(e.error.errorMsg, "Error: " +e.error.errorCode);
 
return;
 
}
 
var data:GetInfoData=e.data as GetInfoData;
 
var friendCollection:FacebookUserCollection=data.userCollection as FacebookUserCollection;
 
createList(friendCollection);
 
}
 
private function createList(data:FacebookUserCollection):void
 
{
 
_friendsCollection=new ArrayCollection();
 
for (var i:int=0; i &lt; data.length; i++)
 
{
 
_friendsCollection.addItem(data.getItemAt(i));
 
}
 
friendsList.dataProvider=_friendsCollection;
 
}
&lt;mx:Button label="get Friends"
 
click="getFriends()" x="10" y="66"/&gt;t;
 
Also we need to put in an itemRender to the TileList (for more info on itemRenders)
 
//This will allow you to show each friend's picture and when you hover over it will tell you there name.
 
&lt;mx:TileList id="friendsList" columnCount="4" rowCount="1" width="400" height="400"
 
labelField="pic_big" allowMultipleSelection="false" x="10" y="126"&gt;
 
&lt;mx:itemRenderer&gt;
 
&lt;mx:Component&gt;
 
&lt;mx:Image source="{data.pic_big}"
 
toolTip="{data.name}"/&gt;
 
&lt;/mx:Component&gt;
 
&lt;/mx:itemRenderer&gt;

Step 11: (Almost there) add functionality to the comboBox.

private function closeHandler(event:Event):void
 
{
 
sort();
 
}
 
private function sort():void
 
{
 
var dataSortField:SortField=new SortField();
 
dataSortField.name= sortBox.selectedItem.data as String;
 
if(sortBox.selectedLabel == "Z-A")
 
{
 
dataSortField.descending = false;
 
}
 
else
 
{
 
dataSortField.descending = true;
 
}
 
var numericDataSort:Sort = new Sort();
 
numericDataSort.fields = [dataSortField];
 
_friendsCollection.sort = numericDataSort;
 
_friendsCollection.refresh();
 
}

//don’t forget to add the event handler for the comboBox

&lt;mx:ComboBox dataProvider="{sorts}" id="sortBox" close="closeHandler(event)" x="10" y="96"/&gt;

And we are done. Here is the code in it’s entirety.

		&lt; ![CDATA[
			import com.facebook.commands.notifications.SendEmail;
			import com.facebook.commands.notifications.SendNotification;
			import mx.utils.StringUtil;
			import com.facebook.data.FacebookErrorCodes;
			import mx.controls.Alert;
			import mx.events.ListEvent;
			import mx.events.ItemClickEvent;
			import mx.collections.Sort;
			import mx.collections.SortField;
			import com.facebook.data.users.FacebookUserCollection;
			import mx.collections.ArrayCollection;
			import mx.controls.List;
			import com.facebook.data.friends.GetFriendsData;
			import com.facebook.commands.friends.GetFriends;
			import com.facebook.data.friends.FriendsData;
			import com.facebook.data.friends.FriendsCollection;
			import com.facebook.data.users.GetInfoData;
			import com.facebook.data.users.FacebookUser;
			import com.facebook.events.FacebookEvent;
			import com.facebook.Facebook;
			import com.facebook.utils.FacebookSessionUtil
			import com.facebook.net.FacebookCall;
			import com.facebook.commands.users.GetInfo;
			import com.facebook.data.users.GetInfoFieldValues;
			import com.facebook.data.users.FriendsGetData;
 
			[Bindable]
			private var _friendsCollection:ArrayCollection;
			private var fbook:Facebook;
			private var session:FacebookSessionUtil;
			private var user:FacebookUser;
			private var sortTypes:Object;
			private var infoType:String = "activities";
			private var answerPerson:String;
			private var answer:String;
			private var alert:Alert;
			private var _apiKey:String = "{YOUR APIKEY}";
			private var _secret:String = "{YOUR SECRET CODE}";
			private var _friendSearched:String;
 
			private var quizFriendsCollection:ArrayCollection = new ArrayCollection();
 
			[Bindable]
			public var sorts:ArrayCollection = new ArrayCollection([{label: "A-Z", data: "last_name"}, {label: "Z-A", data: "last_name"}]);
 
			private function init():void
			{
				fbook=new Facebook();
				session=new FacebookSessionUtil(_apiKey, _secret, stage.loaderInfo);
				fbook=session.facebook;
 
				session.login();
				session.addEventListener(FacebookEvent.CONNECT, onConnect);
			/*
			   sortTypes["ASC"] = {label:"A-Z", type:"last_name"};
			 sortTypes["DESC"] = {label:"Z-A", type:"last_name"}; */
			}
 
			private function onConfirmLogin():void
			{
				this.removeChild(loginbutton);
				session.validateLogin();
			}
 
			private function onConnect(e:FacebookEvent):void
			{
				var call:FacebookCall=fbook.post(new GetInfo([fbook.uid], [GetInfoFieldValues.ALL_VALUES]));
				call.addEventListener(FacebookEvent.COMPLETE, onGetInfo);
			}
 
			private function getFriends():void
			{
				var call:FacebookCall=fbook.post(new GetFriends());
				call.addEventListener(FacebookEvent.COMPLETE, onGetFriends);
			}
 
			private function onGetFriends(evt:FacebookEvent):void
			{
				if(evt.error)
				{
					var errorCode:String;
					switch(evt.error.errorCode)
					{
						case FacebookErrorCodes.API_EC_BAD_IP:
							errorCode = "Bad IP";
						break;
 
						case FacebookErrorCodes.API_EC_DEPRECATED:
							errorCode = "API deprecated";
						break;
 
						case FacebookErrorCodes.API_EC_HOST_API:
							errorCode = "API"
						break;
					}
					alert = Alert.show(evt.error.errorMsg, "Error: " + evt.error.errorCode);
					return;
				}
				var friends:FacebookUserCollection=(evt.data as GetFriendsData).friends;
				var uids:Array=[];
				var userFriend:FacebookUser;
				for (var i:int=0; i &lt; friends.source.length; i++)
				{
					userFriend=friends.getItemAt(i) as FacebookUser;
					uids.push(userFriend.uid);
				}
 
				var call:FacebookCall=fbook.post(new GetInfo(uids, [GetInfoFieldValues.ALL_VALUES]));
				call.addEventListener(FacebookEvent.COMPLETE, onHandleFriends);
				//createList(friends);
			}
 
			private function onHandleFriends(e:FacebookEvent):void
			{
 
				if(e.error)
				{
					var alert:Alert = Alert.show(e.error.errorMsg, "Error: " +e.error.errorCode);
					return;
				}
				var data:GetInfoData=e.data as GetInfoData;
				var friendCollection:FacebookUserCollection=data.userCollection as FacebookUserCollection;
				createList(friendCollection);
				quizMe();
			}
 
			private function onGetInfo(e:FacebookEvent):void
			{
				for (var i:int=0; i &lt; (e.data as GetInfoData).userCollection.length; i++)
				{
					user=(e.data as GetInfoData).userCollection.getItemAt(i) as FacebookUser;
					title.text="Hello " + user.first_name + " " + user.last_name;
				}
 
			}
 
			private function createList(data:FacebookUserCollection):void
			{
				_friendsCollection=new ArrayCollection();
				for (var i:int=0; i &lt; data.length; i++)
				{
					_friendsCollection.addItem(data.getItemAt(i));
				}
				friendsList.dataProvider=_friendsCollection;
			}
 
			private function closeHandler(event:Event):void
			{
				sort();
			}
 
			private function sort():void
			{
				var dataSortField:SortField=new SortField();
				dataSortField.name= sortBox.selectedItem.data as String;
 
				if(sortBox.selectedLabel ==  "Z-A")
				{
					dataSortField.descending = false;
				}
				else
				{
					dataSortField.descending = true;
				}
 
				 var numericDataSort:Sort = new Sort();
                numericDataSort.fields = [dataSortField];
				_friendsCollection.sort = numericDataSort;
                _friendsCollection.refresh();
 
			}
 
		]]&gt;

The next tutorial will be searching for a specific friend and sending them a message.

Here are some links for extra reading.

Item Renderers

Event Handlers

Heck, just read everything in here to get an understanding of Flex if you don’t have one.

4 comments June 24th, 2009

Guitar Synth for Flash

guitarsynth

Andre Michelle has created a guitar synth that sounds AMAZING.

It’s done w/o sampling audio, just math and FP10.

http://lab.andre-michelle.com/karplus-strong-guitar

2 comments February 27th, 2009

Abstract Thermometer AIR app

So over the last few months I’ve been messing around with Adobe AIR. The first thing that I worked on was what I was called at the time Abstract Weather Bug. I then noticed that the title was too long.

Look the title is not important. The way the this app works. Is you open the setting slider and enter in your zip, low and high temp scale, Fariehiet or Celsius, and the click GO.

You have the option to save your setting and intervals to which it will check the temperature again.

It then will display a color some were between a gradient of pure blue and red. Post coming soon explaining some of how to create a color scale.

I’m not really a designer (planning to work on that this year) so it doesn’t look awesome.

Add comment January 22nd, 2009

Roman Numeral/Arabic Convertion AIR App – Johnny V Now Available

Merry Christmas, I got you guys present.

I was looking for a need to make an AIR app, though this isn’t the best one, I turned my converter class into one. Introducing Johnny V.

Add comment December 25th, 2008

How to convert Roman Numerals and Arabic numbers in ActionScript 3

This past week I worked on a porting exercise. I have always wanted to find out how you convert Roman Numerals to Arabic numerals and vice versa. So I starting searching and found a bunch of bloated code for converting these numbers then I stumbled on this page.

So in a few hours of screwing around w/ the loops (typing this correctly took a bit) I got it ported. Porting is fun cause all you have to do is translate.

Here is the zip flie and Here is the class.

package com.joshspoon.etc.utils
{
	public class NumberUtils
	{
		public function NumberUtils(){}
 
		public static function romanize(num:int):String {
			var numerals:Array = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X",
										"IX", "V", "IV", "I"];
 
			var numbers:Array  = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
 
			var lookup:Object = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1}
 
			var roman:String = "";
 
			var i:int;
 
			  for( i = 0; i < numbers.length - 1; i++)
			  {
				while(num >= numbers[i])
				{
					roman += numerals[i];
					num -= numbers[i];
				}
			  }
			  return roman;
			}
 
		public static function deromanize( roman:String ):int {
 
			var numerals:Array = ["I", "V", "X", "L", "C", "D", "M"];
 
			var numbers:Array  = [1, 5, 10, 50, 100, 500, 1000];
 
			var roman:String = roman.toUpperCase();
 
			var arabic:int = 0;
 
			var i:int = roman.length;
 
		    var compare1:int;
			var compare2:int;
 
			while (i--) {
 
		  	var letter:String;
	  		var listLetter:String;
 
		  	for (var j:int = 0; j < = numerals.length - 1; j++)
		  	{
		  		letter = roman.charAt(i);
		  		listLetter = numerals[j];
		  		if(listLetter == letter)
		  		{
		  			compare1 = numbers[j];
		  		}
		  	}
 
		  	for (j = 0; j <= numerals.length - 1; j++)
		  	{
		  		letter = roman.charAt(i + 1);
		  		listLetter = numerals[j];
		  		if(listLetter == letter)
		  		{
		  			compare2 = numbers[j];
		  		}
		  	}
 
		    if (compare1 < compare2 )
		      arabic -= compare1;
		    else
		      arabic += compare1;
		  }
		  return arabic;
		}
 
	}
}

2 comments December 17th, 2008

Flash Player 10 Pure Flash Keyboard using SampleDataEvent

Update 10/23/2008

So a bit has changed w/ Flash Player 10 Public Release, I found out that the dynamic sound event changed, again, so I had to make some changes.

Flash Player 10 Public Release Needed

Here is the piano. Once I can build it w/ Air I’ll make it into simple app. I would suggest downloading the swf and running it in your standalone flash player. The keyboard is huge.

I have a couple of ideas to to advance this keyboard:

  1. Decoupling functionality
  2. recording of sound
  3. sustain pedal
  4. pitch ben
  5. modulation
  6. get out an alpha version of the code.

If you have some ideas I’d love to hear them. Please leave me a comment.

5 comments September 3rd, 2008

Using Flash Player 10 to produce Dynamic Musical Notes

image of swf flash player 10 guitar tunerSo after 13 year of off and on drumming I have learned a thing or two about music. Not much about tuning a guitar. Thanks to a class that I got a D in, Musical Acoustics, I know every note produces a frequency and a wavelength. With that you can now you Flash to produce a frequency and that is what I did, the six notes from left to right are the notes of a regularly tuned guitar.

Since I lost my Musical Acoustics book from UNT I had to look it up to find the Frequency of All Notes

and that pick the ones I wanted starting w/ E4.

So if you don’t have a guitar tuner…here you go.

View Code:

[as]

package
{
import flash.display.*;
import flash.events.*;
import flash.media.Sound;
import flash.text.TextField;

public class GuitarTuner extends Sprite
{
private var _key1:Sprite;
private var _key2:Sprite;
private var _key3:Sprite;
private var _key4:Sprite;
private var _key5:Sprite;
private var _key6:Sprite;

private var _sound:Sound;
private var _note:Number = 0;
private var noise:Number = 0;
private var text:TextField = new TextField();

//Constants
private static const E4:String = “E4″;
private static const A4:String = “A4″;
private static const D4:String = “D5″;
private static const G5:String = “G5″;
private static const B5:String = “B5″;
private static const E6:String = “E6″;

public function GuitarTuner()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
_key1 = makeKey();
_key1.name = GuitarTuner.E4;
_key1.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
addChild(_key1);

_key2 = makeKey();
_key2.name = GuitarTuner.A4;
_key2.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
addChild(_key2);
_key2.x = spaceFromSibling(_key1, _key2);

_key3 = makeKey();
_key3.name = GuitarTuner.D4;
_key3.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
addChild(_key3);
_key3.x = spaceFromSibling(_key2, _key3);

_key4 = makeKey();
_key4.name = GuitarTuner.G5;
_key4.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
addChild(_key4);
_key4.x = spaceFromSibling(_key3, _key4);

_key5 = makeKey();
_key5.name = GuitarTuner.B5;
_key5.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
addChild(_key5);
_key5.x = spaceFromSibling(_key4, _key5);

_key6 = makeKey();
_key6.name = GuitarTuner.E6;
_key6.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
addChild(_key6);
_key6.x = spaceFromSibling(_key5, _key6);

addChild(text);
text.x = 300;

}
private function onCallback(e:SamplesCallbackEvent):void
{
for(var i:uint=0; i<512; i++)
{
noise += _note/ 44100;

var sample:Number = noise * Math.PI * 2;
_sound.samplesCallbackData.writeFloat(Math.sin(sample));
_sound.samplesCallbackData.writeFloat(Math.sin(sample));
}
}

private function onClick(evt:MouseEvent):void
{

_sound = new Sound();
_sound.addEventListener(Event.SAMPLES_CALLBACK, onCallback);
_sound.play();
var sprite:Sprite = Sprite(evt.currentTarget);
switch(sprite.name)
{
case “midC”:

_note = 277.18;

break;

case GuitarTuner.E4:

_note = 329.63;

break;

case GuitarTuner.A4:

_note = 440.00;

break;

case GuitarTuner.D4:
_note = 587.33;
break;

case GuitarTuner.G5:
_note = 783.99;
break;

case GuitarTuner.B5:
_note = 987.77;
break;

case GuitarTuner.E6:
_note = 1318.51;
break;
}

text.text = String(_note);

}

private function makeKey():Sprite
{
var key:Sprite = new Sprite()
key.graphics.lineStyle(1, 0×000000);
key.graphics.beginFill(0xFFFFFF, 1);
key.graphics.drawRect(0, 0, 20, 50);
key.graphics.endFill();
return key;
}

public function spaceFromSibling(sibling:DisplayObject, target:DisplayObject,
coordinate:String = “x”, distance:Number = 0):Number
{
var value:int;

switch(coordinate)
{
case “x”:
value = sibling.x + sibling.width + distance;
break;

case “y”:
value = sibling.y + sibling.height + distance;

break;
}

return Math.floor(value);
}
}
}[/as]

If this code doesn’t make sense check out Lee Brimelow’s tutorial on Dynamic Sound.

1 comment May 20th, 2008

Flash Player 10 Dynamic Sound Generation

I miss writing classes w/ 50 or so lines of code and here is one. This is a take off of Lee Brimelow’s Example of Dynamic Sound Generation. I’m using the BitmapData to create a tone.

[as]

package
{
import flash.display.*;
import flash.events.*;
import flash.media.*;
import flash.net.URLRequest;
import flash.system.Capabilities;
import flash.text.TextField;

public class DynamicSound extends Sprite
{
private var sound:Sound;
private var noise:Number = 0;
private var _loader:Loader;
private var _bm:Bitmap;
private var _verText:TextField;
public function DynamicSound():void
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
_verText = new TextField();
_verText.text = Capabilities.playerType + ” (” + Capabilities.version + “)”;
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
_loader.load(new URLRequest(”http://www.scarlet.nl/~ivo/photo_ASTRO3.JPEG”));

}

private function onComplete(evt:Event):void
{
_bm = Bitmap(_loader.content);
addChild(_bm);
addChild(_verText);
sound = new Sound();
sound.addEventListener(Event.SAMPLES_CALLBACK, onCallback);
sound.play();
}
private function onCallback(e:SamplesCallbackEvent):void
{
for(var i:uint=0; i<512; i++)
{
noise += _bm.bitmapData.getPixel(mouseX, mouseY)/ 44100;
var sample:Number = noise * Math.PI * 2;
sound.samplesCallbackData.writeFloat(Math.sin(sample));

sound.samplesCallbackData.writeFloat(Math.sin(sample));
}
}
}
}

[/as]

Quick and Dirty!

1 comment May 20th, 2008

How to load Pixel Bender in Flash Player 10

Hey so I spent most of the weekend trying to get Senocular’s tutorial on loading .pbj into flash player 10.

For some reason it wasn’t working for me so I decided to download Pixel Bender Preview Release and copy the file’s source code and export it (File > Export Pixel Bender…for Flash) and it worked so I wanted to post it. Just in case some one had the same problem.

AS FILE:

[as]package {
import flash.display.*;
import flash.events.*;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.getTimer;

public class astro2 extends Sprite
{

// image for shader fill
private var _bitmap:Bitmap;

// shader fill shader; it will use
// the image as an input
private var _shader:Shader;

// loader to load pixel bender bytecode
// for shader instance
private var _shaderLoader:URLLoader

private var _loader:Loader

public function astro2()
{
//load image
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImgLoad, false, 0, true);
_loader.load(new URLRequest(”http://bp2.blogger.com/_Y8m29ZLX5ag/RarR3rcAVwI/AAAAAAAAAL4/dtA7xOMrI4g/s400/ASTRO_jpg.jpg”));

}

//once loaded load Pixel Bender File
private function onImgLoad(evt:Event):void
{
_bitmap = Bitmap(_loader.content);

_shader = new Shader();
_shaderLoader = new URLLoader();

_shaderLoader.dataFormat = URLLoaderDataFormat.BINARY;
_shaderLoader.addEventListener(Event.COMPLETE, shaderLoaded);
_shaderLoader.load(new URLRequest(”test.pbj”));
}

// shaderLoader complete handler
private function shaderLoaded(event:Event):void {

// set up shader

_shader.byteCode = _shaderLoader.data as ByteArray; // error if invalid
_shader.data.src.input = _bitmap.bitmapData; // image input
_shader.data.size.value = [100]; // constant size
_shader.data.fade.value = [.5]; // constant fade value

// draw the shader every frame
addEventListener(Event.ENTER_FRAME, drawKaleidoscope);

}

// enterframe handler
private function drawKaleidoscope(event:Event):void {
// base position on mouse location
_shader.data.position.value = [mouseX, mouseY];
// rotate constantly over time
_shader.data.angle.value = [getTimer()/500];

// draw a rectangle with the shader fill
graphics.clear();
graphics.beginShaderFill(_shader);
graphics.drawRect(0,0,300,250);
}
}
}[/as]

and the Pixel Bender code:

kernel Kaleidoscope
< namespace : “Petri Leskinen”;
version : 1;
vendor : “”;
description : “kaleidoscope -effect, rectangular”;
>
{
parameter float4 fadeColor
<
minValue: float4(0,0,0,0);
maxValue: float4(1,1,1,1);
defaultValue: float4(0,0,0,1);
description: “Fade color”;
>;
parameter float2 position
<
minValue: float2(0,0);
maxValue: float2(2880,2880);
defaultValue: float2(250,280);
description: “Center point”;
>;

parameter float size
<
minValue: float(1);
maxValue: float(500);
defaultValue: float(75);
description: “Size”;
>;

parameter float fade
<
minValue: float(0.5);
maxValue: float(1.0);
defaultValue: float(1.0);
description: “Fade”;
>;

parameter float angle
<
minValue: float(-3.14159);
maxValue: float(3.14159);
defaultValue: float(0.5);
description: “Rotation angle”;
>;

input image4 src;
output pixel4 dst;

void evaluatePixel()
{
float sina = sin(angle);
float cosa = cos(angle);

float2 newC = position – size/2.0* float2(cosa+sina, cosa-sina);

// mx matrix for rotation and scaling
// mxR reverse transformation
float2×2 mx = float2×2( cosa,sina,-sina,cosa) /size;
float2×2 mxR = float2×2( cosa,-sina,sina,cosa) *size;

// coordinate p1 on the new coordinate system,
// on the center area 0.0 < p1.x < 1.0 , 0.0 < p1.y < 1.0
float2 p1 = mx * (outCoord() -newC);

// p2 integer part, p1 only decimal part,
// which maps every pixel to the center area
float2 p2 = floor(p1);
p1 = fract(p1); // p1 -= p2;

// p3 dislocation for mirroring,
// mirrored if integer part odd
float2 p3 = 1.0-2.0*p1;
p1.x += mod (p2.x,2.0) > 0.0 ? p3.x : 0.0 ;
p1.y += mod (p2.y,2.0) > 0.0 ? p3.y : 0.0 ;

// reverting to the main coordinate system, sampling and mixing the pixel
p1 = newC + mxR*p1;
dst = mix( fadeColor, sampleLinear(src,p1) ,
pow ( fade,abs(p2.x)+abs(p2.y)) );

}
}

Add comment May 19th, 2008

How to compile and examples for Flash Player 10 or ASTRO BETA

As many of you know ASTRO is in Public beta.

Download browser plugin

Here are some links on how to compile:

Text instruction – by Mike Chanmbers

Video Instruction – by Lee Brimelow

Flash Magizine Article

A promising sound example:

flash produced sound example – by Keith Peters

Here is my “3D” example, quick and dirty:

[as]

package {
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Vector3D;
import flash.net.URLRequest;

public class ASTRO extends Sprite
{

private var _loader:Loader;
private var mc:MovieClip;
public function ASTRO()
{

stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.EXACT_FIT;
_loader = new Loader()
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete, false, 0, true);
_loader.load(new URLRequest(”record.gif”));

}

private function loadComplete(evt:Event):void
{

mc = new MovieClip();
mc.rotationY = 0;
mc.rotationZ = 0;

stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove, false, 0, true);
mc.opaqueBackground = true;
_loader.x = – (_loader.width * 0.5);
_loader.y = – (_loader.height * 0.5);
mc.addChild(_loader);
mc.x = (_loader.width * 0.5);
mc.y = (_loader.height * 0.5);
addChild(mc);

}

private function onMove(evt:MouseEvent):void
{
mc.rotationZ = stage.mouseY;
mc.rotationX = stage.mouseX

}
}
}
[/as]

Also here are some classes that I saw through code completion. I don’t really know what to do with them yet. Maybe someone else will and will let me know (I have too much work and GTAing to do :) ).

  • flash.text.engine Package (over a dozen classes)
  • __AS3__.vec.Vector (that is wierd)
  • flash.display.GraphicsBitmapFill
  • flash.display.GraphicsPathCommand
  • flash.display.TriangleCulling (that sounds interesting)
  • flash.geom.Vector3D
  • flash.filters.ShaderFilter

Happy Coding!

1 comment May 16th, 2008

Previous Posts


    Blog Calendar

    March 2010
    M T W T F S S
    « Jun    
    1234567
    891011121314
    15161718192021
    22232425262728
    293031  

    Posts by Month

    Posts by Category