var assetLoader:URLLoader = new URLLoader();
assetLoader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
assetLoader.addEventListener(Event.COMPLETE, completeHandler);
function progressHandler(e:Event):void
{
trace(e.currentTarget.bytesLoaded + " / " + e.currentTarget.bytesTotal);
}
function completeHandler(e:Event):void
{
trace("completeHandler:" + e.currentTarget + " :: " + e.currentTarget.dataFormat + " :: " + e.currentTarget.data);
}
Tag Archive for as3
Using URLLoader for Text and XML
Category: Uncategorized |
Tags: as3
Using Loader for SWFs, JPEGs, GIF, and PNGs
/********************************
Event Listeners
********************************/
var imgLoader:Loader = new Loader();
initBasicListeners( imgLoader );
imgLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler, false, 0, true);
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler, false, 0, true);
imgLoader.load(new URLRequest(asset));
//These Event Listeners are used a lot so let's try to minimize redundancies
function initBasicListeners(dispatcher:IEventDispatcher):void
{
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler, false, 0, true);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler, false, 0, true);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler, false, 0, true);
}
/********************************
Event Handlers
********************************/
function httpStatusHandler (e:Event):void
{
//trace("httpStatusHandler:" + e);
}
function securityErrorHandler (e:Event):void
{
trace("securityErrorHandler:" + e);
}
function ioErrorHandler(e:Event):void
{
trace("ioErrorHandler: " + e);
}
function progressHandler(e:Event):void
{
trace(e.currentTarget.bytesLoaded + " / " + e.currentTarget.bytesTotal);
}
function onCompleteHandler (e:Event):void
{
trace("imgCompleteHandler:" + e.currentTarget.content + " " + e.currentTarget.loader);
addChild( e.currentTarget.loader );
}
Category: Uncategorized |
Tags: as3
Custom Preloader
/***************************
Event Handler
***************************/
addEventListener(Event.ENTER_FRAME, loading);
/***************************
Function
***************************/
function loading(e:Event)
{
var bytestotal = stage.loaderInfo.bytesTotal;
var bytesloaded = stage.loaderInfo.bytesLoaded;
var percent = Math.round(bytesloaded * 100/bytestotal);
mc_with_100_frame_animation.gotoAndPlay(percent);
if (bytesloaded >= bytestotal)
{
gotoAndStop(2);
removeEventListener(Event.ENTER_FRAME, loading);
removeChild(custom_animation);
}
}
stop();
Category: Uncategorized |
Tags: as3
Flash Printing Basics
var myPrintJob:PrintJob = new PrintJob();
var result:Boolean = myPrintJob.start();
if (result) {
myPrintJob.addPage("invitation_mc", {xMin:30, xMax:250, yMin:27, yMax:300}, {printAsBitmap:true}, 2);
myPrintJob.addPage("map_mc", null, {printAsBitmap:false}, 1);
myPrintJob.addPage(1, null, {printAsBitmap:true}, null);
myPrintJob.addPage("guestList_mc", null, {printAsBitmap:true}, 4);
for(i = 1; i <= myMovieClip_mc._totalframes; ++1){
myPrintJob.addPage("myMovieClip_mc", null, null, i);
}
myPrintJob.send();
delete myPrintJob;
} else {
//User does not have printer or user canceled print action
}
Calling Google’s Urchin Tracker from Flash
//ExternalInterface Send Method
ExternalInterface.call("urchinTracker",trackingStr);
//Strip Out Spaces and Replace with Underscores
var pattern:RegExp = / /gi;
//Formulate Tracking String
var formattedVideoTitle:String = _videoTitle.replace(pattern, "_");
var trackingStr:String = "/" + _trackingPath + "/" + formattedVideoTitle;
//URL Request Send Method
sendToURL(new URLRequest("javascript:urchinTracker('"+trackingStr+"');");
Category: Uncategorized |
Tags: as3
Create CDATA tags between XML nodes using AS
function cdata(theURL:String):XML
{
var x:XML = new XML("<![CDATA[" + theURL "]]>");
return x;
}
<the_url>{cdata("http://some.com?var=someval&foo=bar")}</the_url>
Basic Timer example
var timer:Timer = new Timer(1000, 2);
timer.addEventListener(TimerEvent.TIMER, blah);
timer.start();
function blah(e:TimerEvent):void{
trace("Times Fired: " + e.currentTarget.currentCount);
trace("Time Delayed: " + e.currentTarget.delay);
}
Category: Uncategorized |
Tags: as3
Sending Data using POST
var bg_mc:MovieClip = new MovieClip();
bg_mc.graphics.beginFill(0xFF0000, 1);
bg_mc.graphics.drawRect(0, 0, 100, 100);
bg_mc.graphics.endFill();
bg_mc.x = stage.stageWidth / 2 - bg_mc.width / 2;
bg_mc.y = stage.stageHeight / 2 - bg_mc.height / 2 ;
bg_mc.buttonMode = true;
bg_mc.addEventListener(MouseEvent.MOUSE_DOWN, visitSite);
addChild(bg_mc);
function visitSite(e:MouseEvent):void {
var url:String = "http://api.flickr.com/services/rest/";
var request:URLRequest = new URLRequest(url);
var requestVars:URLVariables = new URLVariables();
requestVars.api_key = "3c84c0ca7f9ae17842a370a3fbc90b63";
requestVars.method = "flickr.test.echo";
requestVars.format = "rest";
requestVars.foo = "bar";
requestVars.sessionTime = new Date().getTime();
request.data = requestVars;
request.method = URLRequestMethod.POST;
var urlLoader:URLLoader = new URLLoader();
urlLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlLoader.addEventListener(Event.COMPLETE, loaderCompleteHandler, false, 0, true);
urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler, false, 0, true);
urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler, false, 0, true);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler, false, 0, true);
for (var prop:String in requestVars) {
//trace("Sent: " + prop + " is: " + requestVars[prop]);
}
try {
urlLoader.load(request);
} catch (e:Error) {
trace(e);
}
}
function loaderCompleteHandler(e:Event):void {
var responseVars = URLVariables( e.target.data );
trace( "responseVars: " + responseVars );
}
function httpStatusHandler( e:HTTPStatusEvent ):void {
//trace("httpStatusHandler:" + e);
}
function securityErrorHandler( e:SecurityErrorEvent ):void {
trace("securityErrorHandler:" + e);
}
function ioErrorHandler( e:IOErrorEvent ):void {
//trace("ORNLoader:ioErrorHandler: " + e);
dispatchEvent( e );
}
Category: Uncategorized |
Tags: as3
Load external .txt and .css
/***************************************
Initialize Variables
***************************************/
var tf:TextField = new TextField();
tf.width = stage.stageWidth;
tf.height = stage.stageHeight;
addChild(tf);
var wordList:Array = new Array();
var textLoader:URLLoader = new URLLoader();
textLoader.addEventListener(Event.COMPLETE, textLoaded);
var cssLoader:URLLoader = new URLLoader();
var css:StyleSheet = new StyleSheet();
/***************************************
Parse Text + Apply External CSS
***************************************/
function cssLoaded(e:Event):void{
css.parseCSS(e.target.data);
tf.styleSheet = css;
for(var i:int = 0; i < wordList.length; i++){
tf.htmlText += "<h4>" + wordList[i] + "</h4>";
}
}
function textLoaded(e:Event):void{
wordList = e.target.data.split("
");
cssLoader.load(new URLRequest("http://www.channelone.com/css/flash_block.css"));
cssLoader.addEventListener(Event.COMPLETE, cssLoaded);
}
textLoader.load(new URLRequest("http://www.channelone.com/fun/swf_band_name_txt.txt"));
Category: Uncategorized |
Tags: as3
Streaming Mp3 Player using Flash Media Server 2
/*******************************
Import Classes
*******************************/
//Allow AS3 to talk to FMS2 AS1
NetConnection.defaultObjectEncoding = ObjectEncoding.AMF0;
/*******************************
Var
*******************************/
var rtmp:String = "rtmp://yourserver.com";
var songList:Array = new Array("You and I", "05 Phantom pt. I");
var nc:NetConnection = new NetConnection();
// nc.objectEncoding = flash.net.ObjectEncoding.AMF0;
var ns:NetStream;
var id3_ns:NetStream;
var nsClient:Object = new Object();
var id3Client:Object = new Object();
var isConnected:Boolean = false;
var currentSong:Number = 0;
var soundXForm:SoundTransform = new SoundTransform();
soundXForm.volume = 0.5;
/*******************************
Event Listeners
*******************************/
prev_btn.addEventListener(MouseEvent.CLICK, prevHandler);
next_btn.addEventListener(MouseEvent.CLICK, nextHandler);
play_mc.addEventListener(MouseEvent.CLICK, toggleButton);
play_mc.addEventListener(MouseEvent.CLICK, pauseHandler);
seekBar_mc.buttonMode = true;
seekBar_mc.addEventListener(MouseEvent.MOUSE_DOWN, seekStartDrag);
seekScrub_mc.buttonMode = true;
seekScrub_mc.addEventListener(MouseEvent.MOUSE_DOWN, seekStartDrag);
volScrub_mc.buttonMode = true;
volScrub_mc.scaleX = (volBar_mc.scaleX / 2);
volScrub_mc.addEventListener(MouseEvent.MOUSE_DOWN, volStartDrag);
volBar_mc.buttonMode = true;
volBar_mc.addEventListener(MouseEvent.MOUSE_DOWN, volStartDrag);
/*******************************
Event Handlers
*******************************/
function prevHandler(e:MouseEvent):void {
prevSong();
}
function pauseHandler(e:MouseEvent):void {
pauseSong();
}
function playHandler(e:MouseEvent):void {
//Play the song based on the position of the seekKnob
playSong(ns.time);
}
function nextHandler(e:MouseEvent):void {
nextSong();
}
function toggleButton(e:MouseEvent) {
// trace(e.target.currentFrame);
//on - 1 :: onOver - 5 :: mute - 10 :: muteOver - 15
if (e.target.currentFrame == 1)
{
e.target.gotoAndStop(10);
} else if (e.target.currentFrame == 5)
{
e.target.gotoAndStop(15);
} else if (e.target.currentFrame == 10)
{
e.target.gotoAndStop(1);
} else if (e.target.currentFrame == 15)
{
e.target.gotoAndStop(5);
}
}
/*******************************
Connect to FMS and play song
*******************************/
//This Handles a Function call made by the Flash Media Server default main.asc
NetConnection.prototype.onBWDone = function(info) {}
NetConnection.prototype.onBWCheck = function() {}
function createConnection(appURL:String):void {
if( !nc.connected){
nc.connect(appURL);
nc.addEventListener( NetStatusEvent.NET_STATUS, netStatusHandler );
nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
}else{
nc.close();
isConnected = false;
}
}
function securityErrorHandler( e ):void{
trace("SecurityError: " + e);
}
//Detect when a connection has been made as well as the status of a playing song
function netStatusHandler( e:NetStatusEvent ):void {
switch( e.info.code ) {
case "NetConnection.Connect.Success":
connectionSuccess( new Event( "success" ) );
break;
case "NetConnection.Connect.Failed":
connectionFailed( new Event( "failed" ) );
break;
case "NetStream.Play.Stop":
// trace("netStatusHandler:code: " + e.info.code);
break;
default:
//trace( "netStatusHandler:code: " + e.info.code );
break;
}
}
function connectionSuccess( e:Event ):void {
//A. Assign that a NetConnection has been made
isConnected = true;
//B. Assign a new NetStream connection
if( ns == null ){
ns = new NetStream(nc);
ns.addEventListener( AsyncErrorEvent.ASYNC_ERROR, catchAll );
ns.addEventListener( NetStatusEvent.NET_STATUS, netStatusHandler );
ns.addEventListener( IOErrorEvent.IO_ERROR, catchAll );
}
//C. Assign a new ID3 Netstream Connection
if( id3_ns == null ) {
id3_ns = new NetStream(nc);
id3_ns.addEventListener( AsyncErrorEvent.ASYNC_ERROR, catchAll );
id3_ns.addEventListener( IOErrorEvent.IO_ERROR, catchAll );
id3_ns.addEventListener( NetStatusEvent.NET_STATUS, netStatusHandler );
}
playSong(0);
}
function connectionFailed( e:Event ):void {
isConnected = false;
}
function catchAll( e:Event ){
trace("
Catch All: " + e + "
");
}
/*******************************
Single callback functions that process the information sent by FMS2
*******************************/
nsClient.onPlayStatus = function( obj:Object ):void{
switch ( obj.code ){
case "NetStream.Play.Switch":
break;
case "NetStream.Play.Complete":
soundCompleteHandler();
break;
default:
for( var a:String in obj ){ trace(a + " " + obj[ a ]); }
break;
}
}
id3Client.onId3 = function( obj:Object ):void{
if(obj["artist"] != undefined){
text_txt.text = "Artist: " + obj["artist"].toString();
}
if(obj["songtitle"] != undefined){
text_txt.text += "
Title: " + obj["songtitle"].toString()
}
for( var b:String in obj ) {
//trace(b + ": " + obj[ b ]);
}
}
function setNetClientLength(length:Number):void{
nsClient.length = length;
}
/*******************************
Song
*******************************/
function prevSong():void {
//A. Close NetStream connection to allow for a new one
ns.close();
//B. If there is no previous song to play, restart the currentSong
if (currentSong > 0) {
currentSong--;
} else {
currentSong = songList.length - 1;
}
//C. Create a new Net Stream. The new Event is simply Fluff
connectionSuccess( new Event("Empty String"));
}
function nextSong():void {
//A. Close the NetStream connection to allow for a new one
ns.close();
//B. If there is another song in the playlist, play on!
if (currentSong < songList.length - 1) {
currentSong++;
}else {
//C. Otherwise return to the first song on the playlist
currentSong = 0;
}
//D. Create a new NetStream connection
connectionSuccess(new Event("Empty String"));
}
function playSong(position:Number):void {
text_txt.text = "";
//A. Ensure that the connection to FMS is open
if (!isConnected) { createConnection(rtmp); }
//B. Find the ID3 Information of the Mp3
id3_ns.play("id3:" + songList[currentSong]);
//C. Reassign the id3Client:Object to re-catch any ID3 info
id3_ns.client = id3Client;
//C. Play the new NetStream connection
//play(songName, postion in Seconds:Number, duration in seconds:Number, flush:Boolean -> false means play the next song)
ns.play("mp3:" + songList[currentSong], position);
//D. Reassign the nsClient:Object to ensure the catch of the onPlayStatus
ns.client = nsClient;
//E. Adjust the Volume
ns.soundTransform = soundXForm;
//E. Retreive the Length of the Song from FMS and set it to nsClient.length
nc.call("getStreamLength", new Responder(setNetClientLength), "mp3:" + songList[currentSong]);
//F. Begin tracking the position of the song for the status bar
seekBar_mc.addEventListener(Event.ENTER_FRAME, songPosition);
}
function pauseSong():void {
ns.togglePause();
}
function soundCompleteHandler():void {
trace("soundCompleteHandler");
//Garbage Collection
seekBar_mc.removeEventListener(Event.ENTER_FRAME, songPosition);
//This resets the Progress Bar back to 0
songPosition(new Event("Empty String"));
//Flip the Play/Pause button back to play
play_mc.gotoAndStop("play");
//Repeat the song
nextSong();
}
/*******************************
Volume
*******************************/
function volStartDrag(e:MouseEvent):void {
volumeUpdate(e);
volBar_mc.addEventListener(MouseEvent.MOUSE_MOVE, volumeUpdate);
volScrub_mc.addEventListener(MouseEvent.MOUSE_MOVE, volumeUpdate);
stage.addEventListener(MouseEvent.MOUSE_UP, volumeStopDrag);
}
function volumeStopDrag(e:MouseEvent):void {
volBar_mc.removeEventListener(MouseEvent.MOUSE_MOVE, volumeUpdate);
volScrub_mc.removeEventListener(MouseEvent.MOUSE_MOVE, volumeUpdate);
stage.removeEventListener(MouseEvent.MOUSE_UP, volumeStopDrag);
}
function volumeUpdate(e:MouseEvent):void{
//Calculate the Distance Between the Mouse (e.stageX) and the volBar_mc.x
var dist:Number = ((e.stageX - volBar_mc.x) / volBar_mc.width);
if (dist >= 0 && dist <= 1){
//Adjust the Volume Bar GUI
volumeBarUpdate(dist);
//Adjust the Sound Volume
soundXForm.volume = dist;
ns.soundTransform = soundXForm;
}
}
function volumeBarUpdate(dist:Number):void{
volScrub_mc.scaleX = (dist);
}
/*******************************
Seek
*******************************/
function seekStartDrag(e:MouseEvent):void {
//A. Jump to the spot in the song where the user clicked
seekUpdate(e);
//A. Remain seeking while the Mouse is Still Down and Moving
seekBar_mc.addEventListener(MouseEvent.MOUSE_MOVE, seekUpdate);
seekScrub_mc.addEventListener(MouseEvent.MOUSE_MOVE, seekUpdate);
//C. Self Destruct
stage.addEventListener(MouseEvent.MOUSE_UP, seekStopDrag);
}
function seekStopDrag(e:Event):void {
seekScrub_mc.removeEventListener(MouseEvent.MOUSE_MOVE, seekUpdate);
seekBar_mc.removeEventListener(MouseEvent.MOUSE_MOVE, seekUpdate);
stage.removeEventListener(MouseEvent.MOUSE_UP, seekStopDrag);
}
function seekUpdate(e:MouseEvent):void {
//A. If a user clicks a new part of the song, you must first seek() then update the Progress Bar
var dist:Number = ((e.stageX - seekBar_mc.x) / seekBar_mc.width);
//B. Seek the spot
ns.seek(Math.floor(nsClient.length * dist));
//C. Upate the Progress Bar
seekBarUpdate(dist)
}
function songPosition(e:Event):void{
var dist:Number = ns.time / nsClient.length;
if (!isNaN(dist)) {
seekBarUpdate(dist);
} else {
seekBarUpdate(0);
}
}
function seekBarUpdate(dist:Number){
//A. Adjust the GUI
seekScrub_mc.scaleX = dist;
}
/*******************************
Launch the Application on Frame(0)
*******************************/
addFrameScript(0, createConnection(rtmp));