logo

Archive for as3 Archives - Purple Squirrels


Converting video with FFmpeg and Adobe AIR
February 4, 2013 ~ Posted to ActionScript, AIR, Flash, NativeProcess, Video
vc

Something I have been wanting to do for a while now is build a video converter into my Module Builder to enable automatic conversion of video into the various web friendly formats but I could never find a way to do it.

Over the weekend I discovered this tutorial on playing back any video in Adobe AIR. The tutorial runs through how to set up a NativeProcess to hook into FFmpeg to stream video from any format into FLV. FFmpeg is an open source media library for playback and conversion of almost any type of video or audio and is used by VLC and many other applications. I finally had a possible way of converting video within an AIR app! And one of the great things about this is since its using the NativeProcess API the conversion works asynchronously and the app doesn’t lock up while its converting.

Read More…

04 FEB


Uploading video from iPad to server with AIR for iOS
January 24, 2013 ~ Posted to ActionScript, AIR, Flash, Interactive, iOS, PHP
IMG_4719

In this part 2 post following on from Record and play back video with AIR for iOS on iPad I will show you how to take your freshly recorded video and upload it to a web server using PHP.

Assuming you have a MovieClip or some other button labeled ‘uploadbtn’ you first need to add a click event handler to it to trigger the upload.

uploadbtn.addEventListener(MouseEvent.CLICK, onUpload);

Now for the click handler:

function onUpload(e:MouseEvent):void
{
    // create a URLRequest for the PHP file on you server (we'll get to the PHP later)
    var URLrequest:URLRequest = new URLRequest("http://www.yourdomain.com/uploadFile.php");
   
    // videoFile is a File object we created in the last post which references the recorded video
    // attach the various listeners for errors, progress, complete
    videoFile.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadDataComplete);
    videoFile.addEventListener(ProgressEvent.PROGRESS, progressHandler);
    videoFile.addEventListener(IOErrorEvent.IO_ERROR, handleError);
    videoFile.addEventListener(Event.COMPLETE, completeHandler);
   
    // call upload on the File object and pass in the URLRequest
    videoFile.upload(URLrequest);
}

Now we can create the handlers for the attached listeners:

function progressHandler(e:ProgressEvent):void
{
    // just tracing the percentage of progress - you could show it in a progress bar
    trace("Uploading... " + Math.ceil(100 * (e.bytesLoaded / e.bytesTotal)) + "%");
}

function completeHandler(e:Event):void
{
    // upload process is complete
    trace(videoFile.name + " has been uploaded.\n");
}

function uploadDataComplete(e:DataEvent):void
{
    //everything is complete, trace the message returned from the PHP script which is in XML format
    var xml:XML = new XML(e.data);
   
    trace(xml.message);
}



function handleError(e:IOErrorEvent):void
{
    // simple error handler traces the error
    trace("Upload Error:" + e.text);
}

That is all that is required for the ActionScript side of things. Now for the PHP script. This is a very basic script and you should provide some security and validation on any production code.

All you need to do is save this into a blank PHP file and upload it to your server to the location matching the address in you URLRequest above.

<?php

// variable for return message
$message = "";

// the directory to place the video relative to this PHP script
$directory = "uploads/";

// get the number of files already in the directory and increment the number for the new one
// video from the iPad is always .MOV format
$fileCount = count (glob ($directory."*.MOV"));
$newName = $directory."video" . ( $fileCount + 1) . ".MOV";

// move uploaded file with new name into directory specified above
if (move_uploaded_file($_FILES["Filedata"]["tmp_name"], $newName)){
    // create a successful message if all went ok
    $message =  "<result><status>OK</status><message>$file_name uploaded successfully.</message></result>";
}else{
    // create a failed message if something went wrong
    $message =  "<result><status>FAIL</status><message>$file_name did not upload successfully.</message></result>";
}

echo $message;
?>

That is all that’s required to upload a video from the iPad to a web server. It is surprisingly simple for how hard it was for me to work out.

I hope this helps somebody out!

24 JAN


Virtual Graffiti Wall on Today in the US
January 23, 2013 ~ Posted to ActionScript, AIR, Flash, Interactive, Multitouch
vgwpix

Recently the Virtual Graffiti Wall application (formerly Pixel Perfect) I built for Classy Event Group was featured on the morning show Today in the US. Check out the 2 minute segment in the below video.

The app is built on Adobe AIR and is multi-user/multi-touch enabled. Features include:

  • Stencils (with rotate, move and scale)
  • Spray paint simulation with drips
  • ‘clip art’ stamps (with rotate move and scale)
  • Image gallery hot folder for live photobooth
  • Built in green screen removal with user fine adjustments
  • Customisable sounds for each brush
  • Saving and printing of artwork

The system is available for rental world wide at www.PhotoGraffitiWall.com.

23 JAN


AS3 – Split a camel case string
January 19, 2013 ~ Posted to ActionScript, Flash
shutterstock_112149554

This is a little helper function which takes a string in camel case (camelCase) or pascal case (PascalCase) and splits it into separate words. The capitaliseFirst parameter will capitalise the first character in the first word if the string is in camel case.

Read More…

19 JAN


Record and play back video with AIR for iOS on iPad
December 3, 2012 ~ Posted to ActionScript, AIR, Flash, iOS, StageVideo
IMG_4720

Recently I needed to figure out how to create an iPad app when you can record and play back video from the iPad’s camera, and then upload to it to a server using AIR for iOS. I wasn’t able to find a whole lot of info on it and so I eventually pieced it together from various places. I decided to share the first part of the process here, and I might share the second part in another post later.

I will assume you have a button on the Flash stage called ‘recordbtn’ which the code below will use to fire up the device’s camera.

First we have to set up some variables and check for StageVideo availability:

// use stage video to playback recording
var stageVid:StageVideo;

// variables for displaying the video
var videoFile:File;
var ns:NetStream;
var nc:NetConnection;

// create instance of CameraUI for showing native camera app
var deviceCameraApp = new CameraUI();

// we'll use StageVideo to display the recorded video, first we have to listen for availability
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, onStageVideoAvailability);


function onStageVideoAvailability(e:StageVideoAvailabilityEvent):void
{
    // if StageVideo available
    if (e.availability == StageVideoAvailability.AVAILABLE)
    {
        // get stage video instance
        stageVid = stage.stageVideos[0];

        // create a net connection for playing back the video
        nc = new NetConnection();
        nc.connect(null);
       
        // create a netstream for the net connection       
        ns = new NetStream(nc);
        ns.client = this;
       
        // add click event to record button
        recordbtn.addEventListener(MouseEvent.CLICK, onRecord);
       
        // add event for stage video render state
        stageVid.addEventListener(StageVideoEvent.RENDER_STATE, onRender);
    }
   
}

function onRender(e:StageVideoEvent):void
{
    // when the video is ready to play set the viewport size so we can see the video
    stageVid.viewPort = new Rectangle( 247 , 43 , 529 , 397 ) ;
}

Read More…

03 DEC


AS3 / JS Constrain a value in one line
November 29, 2012 ~ Posted to ActionScript, Javascript
const

Here is a little snippet to constrain a value in a single line. It works by using two nested inline conditionals. The ‘else’ part of the first conditional is another conditional. It may not be the best approach but it works and is much easier and faster to write than two if-else statements.

In English it looks like this:
value = is value greater than max ? set to max, otherwise is value less than min ? set to min, otherwise leave it as is;

// for js - remove the type declarations (:Number)
var minValue:Number = 0;
var maxValue:Number = 100;

value = value > maxValue ? maxValue : (value < minValue ? minValue : value);

29 NOV


AS3 Getting colours blended between two other colours
November 18, 2012 ~ Posted to ActionScript, Flash
grads

Here is another function that can be added to my ColourUtil class. This one gets a specified number of colour steps between two blended colours.

I thought it would be much harder to achieve than it is, luckily the AS3 Color class has the static method interpolateColor which calculates a single colour at a specified position using a ratio value.

The function below is a simplified version of the function found at AS3 Adventure. This blog post also has a much better explanation of the interpolateColor method, and a great demo of the function.

function getColoursBetween(colour1:uint, colour2:uint, steps:int):Array
{
    var arr = [],
        i:uint,
        ratio:Number;
   
    arr.push(colour1);
   
    for (i = 1; i < steps; i++)
    {
        ratio = i / steps;
        arr.push(Color.interpolateColor(colour1,colour2,ratio));
    }
   
    arr.push(colour2);
   
    return arr;
}

18 NOV


AS3 Hex Colour Dodge blending utility
November 12, 2012 ~ Posted to ActionScript, Flash
cdodge

The following is a function that takes two hex colours – a top colour and a bottom colour – and blends them using the Colour Dodge blend mode as found in Illustrator of Photoshop. This is handy for dynamically generating colour variants based on the blend mode. Instead of blending two display objects it simply returns a new hex value using the algorithm of the blend mode.
Read More…

12 NOV


AS3 Easy gapless sound looping solution
November 11, 2012 ~ Posted to ActionScript, Flash
sndas3

If you have come accross the issue of sounds not looping seamlessly in a Flash project then try the following.
Simply offset the start of the sound by 80 milliseconds:

var channel:SoundChannel = new SoundChannel();
var sound:Sound = new Sound();

sound.load(new URLRequest('sound.mp3'));
channel = sound.play(80);

11 NOV


Adding console.log() to AIR’s HTMLLoader
July 13, 2012 ~ Posted to ActionScript, AIR, Flash, Javascript
veins

Here is a little code snipped I thought I’d post for future reference and may help someone else out.

I was using the HTMLLoader class in Adobe AIR to load content and I came across an error where my Javascript was calling console.log(). In the AIR HTMLLoader environment this function does not exist so I had to come up with a way for it to stop throwing errors.

The solution I came up with was to create the console object and add the log function. That way I could trace out any log info or do anything else with it if I need to. So here is the snipped to add console.log to the HTMLLoader.

/* creating the loader object */
var ldr:HTMLLoader = new HTMLLoader();
ldr.load(new URLRequest('path/to/html/file.html'));
ldr.addEventListener(Event.COMPLETE, onLoaded);
addChild(ldr);

/* when load is complete, do the magic */
function onLoaded(e:Event):void
{
    /* Create console object on the window */
    ldr.window.console = {};
    /* add the log function to the console object, this function could do anything with the log data but here I am just tracing it */
    ldr.window.console.log = function(msg){trace(msg)};
   
}

Easy.

13 JUL