Video Player 4 introduces interactive playlists, social sharing and more

video player 4 hero shotI’ve been busy hardening and improving my video player lately and had so many updates for it I decided to upload it to activeden as a new file altogether. After some final bug fixes and testing it’s been approved for sale. I think it’s a huge improvement over the last video player. The video playing part is mainly the same (with a few small adjustments for better usability), but I’ve added tons to this update. It’s online at activeden for live preview and purchase.

An extensively customizable yet simple video player. Create and manage play lists for you video delivery as well as allow viewers to share and socially bookmark the video. Integrate the video into your user experience with javascript integration as well as Google Analytics tracking on the video interaction! Control functionality, layout and colors of the player easily! Plus don’t sweat the embed codes – an embed code generator included!

Check out the legend graphic for some views of the player and the different panes. There is the full video view, the playlist, share and detail panes. You can also view them all in fullscreen mode.

circlecube video player 4 legend

This new player has the following updates:

  • Includes an embed script generator built specifically for this video player! Embed script generator with a Live Preview!
  • Use an external xml playlist or set playlist values in flashvars settings. (No need for xml if you don’t want it)
  • Social Bookmarking with facebook, twitter, delicious, google buzz & linkedin
  • Send emails through the player to share the video with friends
  • Google Analytics Integration (event tracking) – Uses your analytics account on a per video setting in flashvars.
  • All colors fully customizable in flashvars or xml
  • Display video title and description – html content (may contain links) in the detail pane.
  • Video controls also in context menu (right-click menu)
  • Loop the video once, twice however many times you wish and even infinitely!
  • Disable tooltips completely if you wish
  • Keyboard shortcut integration! Press the space bar to pause/play the video just like in most video playback programs.
  • Volume setting cached across sessions for a better user experience
  • Double click video for fullscreen

As well as all that made version 3 video player great as well:

  • Supports flv, f4v and any container format using H.264: mp4, m4a, mov, mp4v, 3GP, 3G2.
  • All images and video loaded externally
  • Run this player without additional files, just pass in the flv path.
  • Supports most image file types: jpg, gif, png.
  • Google Analytics Integration (event tracking) – Uses your analytics account on a per video setting in flashvars.
  • Load any dimension video. Completely resizable
  • Set player width and height
  • Set video width and height
  • Full screen capabilities
  • All colors fully customizable
  • Use a preview/thumbnail image.
  • Auto play option
  • Auto load option – in case you had a bunch of video on one page you wouldn’t want them all to auto load.
  • Video scale/stretching options: none, exact, uniform, fill.
  • Javascript callback functions for loading video and finishing video playback.
  • Show/hide a big play button over the video option
  • Show/hide “vcr” video player controls or have them auto-hide
  • Advanced volume controls, click to mute or drag to desired volume. Volume fades rather than cuts.
  • Support for a logo
  • Controls auto-hide
  • Time code display in current time or elapsed time. click to toggle
  • Tooltips for controls
  • Send video files to player dynamically with javascript integration (with an html link on a page send a video to play)
  • Replay video after complete
  • Progressive play and load displays. Watch as the video loads and see the scrub bar update as you watch.
  • Scrub bar is interactive click and drag. Tooltip to display hovered time.
  • Animated play controls.
  • Buttons states & tooltips.
  • All player graphics are vector shapes and very small in size.
  • Fully rearrange player controls
  • Option to disable fullscreen
  • Display video title and description – html content (may contain links)

Here’s a screenshot of the embed code generator:

embed generator preview

Access the html page URL and swf path from flash with as3

To get the url of the html page that contains the flash/swf file we need a little help from the browser. I’ve written about the following methods before, but they were in as2 with “Get current url to Flash swf using an External Interface call” and “Get Current URL and Query String Parameters to Flash in as2“. In as3, we’ll still need access to javascript in the form of ExternalInterface, so if you want to do this on a site that doesn’t allow javascript you’ll have to keep searching (or jump to the bottom for an alternative method). We don’t need to do anything with the javascript or have access to the pages source code, javascript just has to be enabled, and it works in every browser I have access to. All we do is call a javascript line from within the swf which gets the url in the browser, namely:
window.location.href
That is the javascript we need to call. But we do it from an externalInterface call like so:
ExternalInterface.call("window.location.href.toString")
or to make sure all browsers play nicely we can wrap it in a function in case the browser doesn’t want to execute that as a line, this seems to work more solidly:
ExternalInterface.call("function(){ return window.location.href.toString();}")
also note that we’re specifically applying the toString method, this is needed so the javascript actually executes something and can return it.

Other things you may want to do related to this is getting the query string variables form the url, which also uses externalInterface. You can also use this same method to get the domain, path, protocol, and even referrer. You could use some nice regex or substrings to find these from the full url, but it is already accessible. I can see a potential need for the speed to get the full url and then use internal code to cut it however I need it. But, I’m not convinced that using an external interface call takes that much time (but it’d be an interesting experiment to say the least).

You may want to find the url to the actual swf, and this doesn’t require javascript at all, the swf does know where it is even if it doesn’t know where it is embedded. We can use the loderInfo object and the url property. This returns the url to the swf file regardless of what page or even domain it is embedded on:
this.loaderInfo.url

For ExternalInterface to work in IE you need valid classid and id attributes in the tag. This is one of the reasons I use swfobject to handle my embed codes. It takes care of the Internet Exploder.

If your set up fails it may be because it throws a security error. To solve this to set the param allowScriptAccess to ‘always’ and in your actionscript add your domain, in order to enable the use of ExternalInterface.

[cc lang=”html”]

[/cc]
[cc lang=”actionscript”]
flash.system.Security.allowDomain(sourceDomain)
[/cc]

DEMO

get href url tutorial demo
This demo, gets all of the above mentioned values/properties and more. I threw in what I could think of that may be useful or interesting. It shows a couple ways to get the window location href as well as a way it won’t work. Then there are the rest of the properties available using this same method: href, host, hostname, hash (anchor link ‘#’), pathname (url after the domain), port, protocol, search (query string values), the document title and even referrer. Then from the loaderInfo object we can access the url of the swf as well as other things but most used is the bytesTotal and bytesLoaded. Now check out the demo here (adding an fpo hash and query string to the link just for demonstration purposes, feel free to play with the url and see the values updated.
[cc lang=”actionscript”]
import flash.external.ExternalInterface;

displayText.appendText(‘ExternalInterface.call(“function(){ return document.location.href.toString();}”): ‘ + ExternalInterface.call(“function(){ return document.location.href.toString();}”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“function(){ return window.location.href.toString();}”): ‘ + ExternalInterface.call(“function(){ return window.location.href.toString();}”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.href.toString”): ‘ + ExternalInterface.call(“window.location.href.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.href”): ‘ + ExternalInterface.call(“window.location.href”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.host.toString”): ‘ + ExternalInterface.call(“window.location.host.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.hostname.toString”): ‘ + ExternalInterface.call(“window.location.hostname.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.hash.toString”): ‘ + ExternalInterface.call(“window.location.hash.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.pathname.toString”): ‘ + ExternalInterface.call(“window.location.pathname.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.port.toString”): ‘ + ExternalInterface.call(“window.location.port.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.protocol.toString”): ‘ + ExternalInterface.call(“window.location.protocol.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.search.toString”): ‘ + ExternalInterface.call(“window.location.search.toString”) + “\n”);

displayText.appendText(‘ExternalInterface.call(“function(){ return document.title;}”): ‘ + ExternalInterface.call(“function(){ return document.title;}”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“function(){ return document.referrer;}”): ‘ + ExternalInterface.call(“function(){ return document.referrer;}”) + “\n”);

displayText.appendText(‘this.loaderInfo.url: ‘ + this.loaderInfo.url + “\n”);
displayText.appendText(‘this.loaderInfo.bytesLoaded: ‘ + this.loaderInfo.bytesLoaded + “\n”);
displayText.appendText(‘this.loaderInfo.bytesTotal: ‘ + this.loaderInfo.bytesTotal + “\n”);
[/cc]

Finally a method I’ve used in my video players when I want users to be able to share the link through the player is send an explicit ‘permalink’ in the flashvars or xml playlist. Then the video can be embedded on any site and users can share the original video url. Plus then I don’t have to rely on javascript. I’ve written about flashvars in the past though, so I’ll leave it to you to put 2 and 2 together. Flashvars is one more plug for swfobject to me though, because it makes it so I only have to declare them once and it handles all the browser specific code.

Anyways, this demo has been tested in mac firefox, chrome, safari and windows ie7, ie8, firefox and chrome. If you have a different browser please comment that it works (or not) so we can get a full spectrum, thanks!

Download Source Files

Related tools/resources:

Actionscript (as3) Javascript Communication | Call Flash to and from javascript

Often we need to have different parts of a website talk to each other. This can get tricky when we are using multiple technologies and need the communication in real-time. Going from flash to html is done through javascript on the browser side and in actionscript we use something called ExternalInterface. The ExternalInterface class is an application programming interface that enables straightforward communication between ActionScript and the SWF container– for example, an HTML page with JavaScript or a desktop application that uses Flash Player to display a SWF file. We can send things form actionscript to javascript as well as from the html and javascript into flash and actionscript.

I’ve written about this before. It got old though and I had reports that it was having issues in certain browsers, so I had a minute to look at it and decided it needed a rebuild. This version uses as3 and swfobject. I was tempted to throw jQuery in there as well, but didn’t want to confuse anyone. This is simple javascript. I did have to throw some css3 on it for style though. I did use swfobject because it makes life easier, but it’s not required.

So, just like in as2, communication between actionscript and javascript still requires our friend ExternalInterface to link them but the setup/syntax changed a bit with as3. From the docs here are a few pointers of what we can accomplish with External Interface:

From ActionScript, you can do the following on the HTML page:

  • Call any JavaScript function.
  • Pass any number of arguments, with any names.
  • Pass various data types (Boolean, Number, String, and so on).
  • Receive a return value from the JavaScript function.

From JavaScript on the HTML page, you can:

  • Call an ActionScript function.
  • Pass arguments using standard function call notation.
  • Return a value to the JavaScript function.

It’s really cool that we can pass various data types. Here I’ve got an example that simply sends a string back and forth. We have the actionscript to javascript lane as well as the javascript to actionscript lane. So to set it up we need to know the names of our functions. Here I’ve tried to name them exactly what they are. There is a function in my javascript to both send and receive text to actionscript. Also, there are corresponding functions in my actionscript code: one to send and one to receive. These functions pass the data back and forth.

The magic is set up with the call and addCallback methods of ExternalInterface.

To call a javascript function from actionscript we use the call method. The first argument is the name of the javascript function as a String and any following (optional) arguments are the parameters that are passed to said function. So we need a function in the javascript on that page which is set up to accept some data or at least set up to do something (we don’t actually have to pass data, it could be just a trigger for something on the page). Then in our actionscript we call:
ExternalInterface.call("name_of_js_function", "data passed to js");

Then to go back from javascript to actionscript there is a little bit more set-up involved. We will use the addCallback method here and this sets the actionscript function to be able to accept a call from javascript. The first argument is the function name in javascript (again as a String), and the second argument is the function name in actionscript that you want to be called:
ExternalInterface.addCallback("name_of_js_function", name_of_as3_function);
Then you write your actionscript function to do what you want:
function name_of_as3_function():String {
//do something
return something;
}

Demo

View the actionscrip javascript communication DEMO
If that doesn’t make sense try the demo to see it in action. I’ve got the source code listed on the demo page as well as the working example.

Source Code

JavaScript

[cc lang=”javascript”]
function receiveTextFromAS3(Txt) {
document.getElementById(‘htmlText’).value = Txt;
}
function sendTextToAS3(){
var Txt = document.getElementById(‘htmlText’).value;
var flash = document.getElementById(“as3_js”);
flash.sendTextFromJS(Txt);
document.getElementById(‘htmlText’).value = “”;
}

var flashvars = {};
var params = {};
var attributes = {};
attributes.id = “as3_js”;
//attributes.name = “as3_js”;
swfobject.embedSWF(“AS3_Javascript.swf”, “alt”, “450”, “450”, “9.0.0”, false, flashvars, params, attributes);
[/cc]

HTML

[cc lang=”html”]

[/cc]

Actionscript – AS3

[cc lang=”actionscript”]
import flash.external.ExternalInterface;

//Set up Javascript to Actioscript
ExternalInterface.addCallback(“sendTextFromJS”, receiveTextFromJS);
function receiveTextFromJS(t:String):void {
theText.text = t;
}

//Actionscript to Javascript
function sendTextFromAS3(e:MouseEvent):void {
ExternalInterface.call(“receiveTextFromAS3”, theText.text);
theText.text = “”;
}
button.addEventListener(MouseEvent.CLICK, sendTextFromAS3);
button.buttonMode = true;
[/cc]

Source Files

Download the source files here:
FLA, HTML, SWF, ZIP.

cache woes, how to force an image to refresh or load fresh

The simple trick here is to make the browser think that the image file is new. Most web professionals know that browsers will cache and image and remember it’s url and then if you try to access that url again it will show you the image you already downloaded rather than getting a new copy form the server every time. This is great and helps us surf the web faster overall. Sometimes this can bite us though, specifically when you are trying to show someone an image which you just updated and all they see is the old one. If you are in the business of creating things online and having them approved online, you could run into this situation multiple times before lunch every day. Raise your hand if you’ve had to walk a client though how to clear their cache, fun times right? One more situation when this is helpful is I’ve noticed some browsers (firefox) caching animated gifs, and they will not replay the animation if you refresh the page. But for banners and such sometimes you will want the animated gif to replay on reloading the page. I’ve started using this little trick to keep my pages from caching the images and saving me and clients confusion.

So the browser remembers the url and if you try to get that same url later, it will just display what you’ve already downloaded. The trick is to make the browser think it’s a new url. You can do this pretty easily by adding a query string to the end of the url. Those are the urls that have the file name and then it’s followed by a ‘?’ and some jibberish, for example: my-image-i-dont-want-cached.jpg?version=something. This will work once, but the real trick is to have a unique query string every time. I’ve seen this done with random numbers and a number of other things, but my favorite is to add the date to the url. With the date you know that it will always be unique (as it includes seconds).

There are a couple different ways we can append this to the url. They depend on which technologies we have available to us. It can be done with php or javascript. I prefer the php method because it is created as the page is delivered from the server, while the javascript version is set as the image loads, but either one works and I wouldn’t do this in a production since in that case, we want the cache to lighten the load on our servers.

As long as you understand what cache is and why it’s a good thing to have in most scenarios and you are in one of those exceptions where it’s best not o have it, here’s how to do it.

JS Method

[cc lang=”js”]
function freshimg(image){
if (image.src.indexOf(“?”) == -1)
image.src = image.src + “?v=” + Date();
}
[/cc]
[cc lang=”html”]

JS reload append to img src

[/cc]

PHP Method

[cc lang=”php]

PHP append to img src

” width=”160″ height=”600″ border=”0″ />

[/cc]

wideskyscraper from dummyimage.comHere’s some reference for the Date in javascript and php. Now to see it in action: here are a few examples, although this isn’t the best scenario for them, since these images won’t be changing. I’m just using some dummyimage.com and an animated gif inspired by the same.

Link to view example of how to force a fresh image to load.

Circelcube Video Player 3.0 Stock Flash Video Player at ActiveDen

hero-image

My latest stock flash video player of mine was just added to the database of stock flash items at activeDen. Go check it out and if you like it, download it for use in your projects! I’ve got lots in it for you. I’m using the principles I used as the architect for the video player for stomperNet and then at cornerstone media group in this decked out video player. Go get circlecube’s awesome stock flash video player.

circlecube-video-player-3-preview

An extensively customizable yet simple video player. Integrate the video into your user experience with javascript integration as well as Google Analytics tracking on the video interaction! Control functionality, layout and colors of the player easily! Plus don’t sweat the embed codes – an embed code generator included!

Let your video be the focus!

Features

  • Includes an embed script generator! With options for swfobject implementation or simple valid html object tags (or both)!
  • Embed generator makes setting your settings easy with a Live Preview!circlecube-video-embed-preview
  • Supports flv, f4v and any container format using H.264: mp4, m4a, mov, mp4v, 3GP, 3G2.
  • All images and video loaded externally
  • Run this player without additional files, just pass in the flv path and thumbnail path.
  • Supports most image file types: jpg, gif, png.
  • Google Analytics Integration (event tracking) – Uses on page analytics account or a specified account on a per video setting in flashvars.
    analytics-overview
  • Load any dimension video. Completely resizable
  • Set player width and height
  • Set video width and height
  • Full screen capabilities
  • All colors fully customizable in flashvars
  • Use a preview/thumbnail image.
  • Auto play option
  • Auto load option – in case you had a bunch of video on one page you wouldn’t want them all to auto load.
  • Supports Window Mode options. window, transparent, opaque
  • Video scale/stretching options: none, exact, uniform, fill.
  • Javascript callback functions for loading video and finishing video playback.
  • Show a big play button over the video
  • Show/hide “vcr” video player controls
  • Advanced volume controls, click to mute or drag to desired volume. Volume fades rather than cuts.
  • Support for a logo
  • Controls auto-hide
  • 60k file size
  • Time code display in current time or elapsed time. click to toggle
  • Tooltips for controls
  • Send video files to player dynamically (with an html link on a page send a video to play)
  • Replay video after complete
  • Progressive play and load displays. Watch as the video loads and see the scrub bar update as you watch.
  • Scrub bar is interactive click and drag. Tooltip to display hovered time.
  • Animated play controls.
  • Buttons states & tooltips.
  • All player graphics are vector shapes and very small in size.
  • Fully rearrange player controls
  • Option to disable fullscreen
  • Display video title and description – html content (may contain links)
  • Video controls also in context menu

legend-image

Flashvars and as3

flashvars_as3_thumbFlashvars and actionscript 3! Flashvar is a way that in your html embed codes (object tags) you can send variables and values into your swf file. These variables can then be grabbed internally and used your programming! Examples of these could be images that you want to use in your swf but don’t want to import or hardcode them into the flash file or paths to xml or flv files to use as well. Actionscript 3 has a different procedure than as2 did as to how you read these flashvars from the actionscript side. The embed codes and html side of things are still the same, but in case your new to actionscript altogether, I’ll give an example of the html as well. [cc lang=”html”] [/cc] In actionscript 3 we use the loaderInfo object to access the flashvars. The parameters Object of the loaderInfo will contain all the flashvar variables and values. [cc lang=”actionscript”] this.loaderInfo.parameters [/cc] As an example of something that is visual I’ve created this little app to read some options from flashvars about colors. An app that will read a list of colors and update a box that is on the stage already to those colors with the specified delay. I always have fun with randomness so I threw in the option for random colors as well. This file looks for certain flashvars: color, loop, delay and random. These are the keys or names of the variables and they are followed by the values you want them to hold. Note that flashvars can be set in any order, so you don’t have to start with color and end with random. In this example I’m looking for 4 flashvars specifically (in any order):

  • colors:String – a comma delimited list of hex colors or simply a string “random” for randomly generated colors (the hex for black #000000 needs to be 0x000000 in flash) (default is random)
  • loop:Boolean – whether or not to repeat these colors (default is true)
  • delay:Number – the delay between colors (in seconds). (default is 1 second)
  • random:Boolean – determines whether to cycle through colors in given order or randomize. selecting random overrides the loop to true. (default is false)

This is much more than is required for this example, but I was having fun playing with random colors and timing and options. I figured it doesn’t hurt to show the effect you can have with a couple different variables on one file. Here is an example using the object tags above: [kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/12/flashvars_as3.swf” width=”200″ height=”200″ targetclass=”flashmovie” fvars=”colors=0xFF0000,0x0FF000,0x00FF00,0x000FF0,0X0000FF,0xF0000F&delay=.66&loop=true&random=false”] Get Adobe Flash player [/kml_flashembed] And here are some more (please don’t have a seizure!) Here’s the full source if you’re interested: [cc lang=”actionscript”] /* circlecube.com App to demonstrate the process of getting flashvars from embed code to actionscript (as3) Displays colors specified. looking for 4 flashvars specifically (in any order): colors:String – a comma delimited list of hex colors or simply a string “random” for randomly generated colors (the hex for black #000000 needs to be 0x000000) (default is random) loop:Boolean – wether or not to repeat these colors (default is true) delay:Number – the delay between colors (in seconds). (default is 1 second) random:Boolean – determines wether to cycle through colors in given order or randomize. selecting random overrides the loop to true. (default is false) */ //initialize vars var myflashvars:Object = new Object() var myColors:Array = new Array(“random”); var myLoop:Boolean = true; var myDelay:Number = 1; var randomOrder:Boolean = false; var allRandom:Boolean = false; //read flashvars in actionscript3 //if colors flashvars doesn’t exist use these defaults if (!this.loaderInfo.parameters.colors){ myflashvars = {colors: “random”, delay: 1}; } else{ myflashvars = this.loaderInfo.parameters; } //assign flashvars to variables within flash for (var item:String in myflashvars) { trace(item + “:\t” + myflashvars[item]); if (item == “colors”){ myColors = myflashvars[item].split(‘,’); } else if(item == “loop”){ myLoop = parseBoolean(myflashvars[item]); } else if(item == “delay”){ myDelay = myflashvars[item]; } else if(item == “random”){ randomOrder = parseBoolean(myflashvars[item]); } } //use my variables! if (myColors[0] == “random”){ allRandom = true; } var counter:Timer = new Timer(myDelay * 1000); counter.addEventListener(TimerEvent.TIMER, nextColor); trace (“color number: 0”, “color hex: “+myColors[0]); setColor(myBox, myColors[0]); counter.start(); stop(); function nextColor(e:Event):void{ //cycle through colors if (!allRandom && !randomOrder){ if (counter.currentCount+2 > myColors.length){ if (myLoop == true || myLoop == “true”){ counter.reset(); counter.start(); } else{ counter.stop(); } } trace (“color number: “+counter.currentCount, “color hex: “+myColors[counter.currentCount]); setColor(myBox, myColors[counter.currentCount – 1]); } //randomly select a color from the myColors array else if (!allRandom && randomOrder){ var randomColor = Math.floor(Math.random() * myColors.length); trace (“random number: “+randomColor, “color hex: “+myColors[randomColor]); setColor(myBox, myColors[randomColor]); } //randomly create colors else{ trace (“number: “+counter.currentCount, “color hex: “+myColors[0]); setColor(myBox, myColors[0]); } } function setColor(item:DisplayObject, col):void{ if (col == “random”){ setRandomColor(item); } else{ setHexColor(item, col); } } function setHexColor(item:DisplayObject, col:Number):void { var myColor:ColorTransform = item.transform.colorTransform; //check color bounds if (col > 16777215) col = 16777215; else if (col < 0) col = 0; myColor.color = col; item.transform.colorTransform = myColor; } function setRandomColor(item:DisplayObject):void{ setColor(item, (Math.floor(Math.random() * 16777215))); } function parseBoolean(str:String):Boolean { switch(str.toLowerCase()) { // Check for true values case “1”: case “true”: case “yes”: return true; // Check for false values case “0”: case “false”: case “no”: return false; // If all else fails cast string default: return Boolean(str); } } [/cc]

Tutorial to Create a Responsive Image Scroller in ActionScript 3.0

responsive-images-scroller-as3-thumb

I’ve written a tutorial which is published over at flash.tutsplus. This tutorial demonstrates how to create a horizontally scrolling image viewer and covers xml parsing, loading and resizing external images, and creating intuitive and responsive scrolling!

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/07/image-scroller-example.swf” width=”550″ height=”137″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

So check out the Tutorial to Create a Responsive Image Scroller in ActionScript 3.0 over at flash.tutsplus.com!

sourcedemomilestone

You’ll find full source code available for download as well as the demo files and step by step milestones all throughout the tutorial.

Forthcoming Actionscript Image Scroller Tutorial

image-scroller-thumbnail

Here is a preview of a file I’m writing a tutorial for. It’s nothing groundbreaking, but it deals with many normal tasks and will show my process a bit. This tutorial will show how to create a horizontally scrolling image viewer. It will cover xml loading & parsing, loading & resizing external images to fit into a scrollable container, and creating intuitive and responsive scrolling!

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/07/image-scroller-example.swf” width=”550″ height=”137″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

Let me know what you think, and if there’s anything you want specifically mentioned/explained in it I’ll do my best! Or if you have any ideas of how this could be improved.

Update: The article/tutorial has now been published follow the link to theTutorial to Create a Responsive Image Scroller in ActionScript 3.0

How to use fullscreen in AS3 | Stage Display State Tutorial

fullscreen_tut png
One of the best features of the flash player if you’re doing video is the fullscreen functionality. It has been a question I’ve heard repeatedly. There are limits to what you can do in fullscreen. Such as minimal keyboard support while in fullscreen. But it is perfect for a video player! Who doesn’t want to see a video expanded to full screen mode?

There are a couple things to consider when coding fullscreen into your flash. Remember the hard coded “Press Esc to exit full screen mode.” that Adobe has placed into the flash player. This is untouchable by developers, and the function returns to normal stage display state. So we call the function to go fullscreen, but the exit fullscreen has already been written for us. This can pose a problem though, when we need the player to do something when we exit fullscreen, that is when we want it to do something more than the generic black box function adobe includes.

Steps

  1. specify stage properties
  2. full screen button and listeners
  3. stage fullscreenEvent listener
  4. (functions for each)
  5. allowfullscreen = true

Example

[kml_flashembed fversion=”9.0.28″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/03/fullscreen_tut.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”400″ allowfullscreen=”true”]Get Adobe Flash player

[/kml_flashembed]

1. Stage properties exist that allow us to specify what type of fullscreen we want.  We can have the swf scale to fit the fullscreen area (StageScaleMode.SHOW_ALL), not scale at all (StageScaleMode.NO_SCALE), skew to fit fullscreen (StageScaleMode.EXACT_FIT), and scale to fill fullscreen area (Stage.ScaleMode.NO_BORDER).  We may also edit the alignment of the stage in the fullscreen area; in this example I’m using TOP, but refer to documentation for more options

2. Adobe has placed restrictions on when a swf can enter fullscreen, and has deemed that it must result from a user interaction, a mouse click or keystroke. So create your buttons (or keyListeners). I prefer to have one button to enter fullscreen and another to exit, and have them both call the same function to toggle fullscreen. It gives a clearer communication to the user. I then control the visibility of these buttons depending on the current display state of the stage.

3. Another listener to watch the stage dispaly state. stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreenChange); This will fire every time the stage display state changes. We need this because as I mentioned earlier, when entering fullscreen we use our own function, but the ‘hit esc to exit fullscreen’ functionality is built into the flash player, we can’t update our stage layout or button visibility without watching to catch when the display state is changed. Using this method we can update our stage layout any and every time.

4. Of course flesh out the fullscreenToggle function to include anything else you need.

5. Lastly, for a SWF file embedded in an HTML page, the HTML code to embed Flash Player must include a ‘param’ tag and ’embed’ attribute with the name ‘allowFullScreen’ and value ‘true’, like this:

<object>
    ...
    <param name="allowFullScreen" value="true" />
    <embed ... allowfullscreen="true" />
</object>

The allowFullScreen tag enables full-screen mode in the player. If you do everything else right and don’t include this in your embed codes, fullscreen will not work. The default value is false if this attribute is omitted. Note the viewer must at least have Flash Player version 9,0,28,0 installed to use full-screen mode. Also note that  the simple (ctrl + enter) testing your movie in flash will not allow fullscreen either, you must use the debug tester (ctrl + shift + enter) … or go open the published swf in flash player.

Actionscript

[cc lang=”actionscript”]
stage.scaleMode = StageScaleMode.SHOW_ALL;
stage.align = StageAlign.TOP;

var stageDisplayAdjustCounter:uint = 0;

fsb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
ssb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreenChange);

fsb.buttonMode = true;
ssb.buttonMode = true;

//fullscreen buttons need this to adjust the stage display state.
//pressing escape to exit fullscreen bypasses this function
function fullscreenToggle(e:MouseEvent = null):void {
status.appendText(stageDisplayAdjustCounter+”. fullscreenToggle from “+stage.displayState+”\n”);
//normal mode, enter fullscreen mode
if (stage.displayState == StageDisplayState.NORMAL){
//set stage display state
stage.displayState = StageDisplayState.FULL_SCREEN;
}
//fullscreen mode, enter normal mode
else if (stage.displayState == StageDisplayState.FULL_SCREEN){
//set stage display state
stage.displayState = StageDisplayState.NORMAL;
}
//here we subtract 1 from the counter because it has already incremented (in onFullscreenChange) when we set the display state above

status.appendText((stageDisplayAdjustCounter-1)+”. fullscreenToggle to “+stage.displayState+”\n”);
status.scrollV = status.maxScrollV;

}

//this function is called every and anytime the stage display state is adjusted
//either by pressing our buttons or
function onFullscreenChange(e:FullScreenEvent = null):void {
status.appendText(stageDisplayAdjustCounter+”. onFullscreenChange\n”);
status.scrollV = status.maxScrollV;
if (stage.displayState == StageDisplayState.FULL_SCREEN) {
fsb.visible = false;
ssb.visible = true;
}
else {
fsb.visible = true;
ssb.visible = false;
}

stageDisplayAdjustCounter++;
}

onFullscreenChange();

[/cc]

Source

Download fullscreen_tut.fla file

Random Movement | Brownian revisited for as3

I have had feedback that certain random movements I program are a bit “jumpy”. Such as my old brownian movement tutorial and I really noticed it in my last tutorial, the parallax 3d depth effect tutorial. I’ve been thinking about it and looking around at some code and now have this updated brownian movement example! Updated for as3 as well as making it less jumpy.

as3brownian thumb pngFirst I’ll explain what I’ve found to be the reason of the jumpiness. And then explain and show what can be done to make this movement be more smooth.

So to examine the old jumpy code. Jump back to the first version post here. I think my technique was well thought out here, but the application was poor. It was recalculating the velocities every single frame and then incrementing the coordinate positions by the newly calculated velocities… This is where the jumpiness comes in. Even though the random value was named velocity, it didn’t actually affect the dot’s velocity, it was just a variable that stored the random value used to move the current x/y coordinates.
To help the animation be more smooth, the velocity needs to be more smooth. The velocity, rather than calculating it fresh each frame, should be randomly modified each frame. And then the new velocity will calculate the new ‘random’ position. Another addition is to introduce another force to dampen the velocity over time, so things don’t get too crazy…

Steps:

  1. Modify velocity randomly
  2. With velocity and current position, calculate a new position
  3. Dampen the velocity

Example:

Here I have a velocity for the x coordinate as well as the y. I’m also experimenting with a z velocity. This adjusts the alpha and scale for depth perception. It doesn’t actually edit the depth or layer the dot shows up on the stage however… keyword here: experimenting. 🙂
[kml_flashembed fversion=”8.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/02/as3random_brownian_movement.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”550″ wmode=”transparent”]

Get Adobe Flash player

[/kml_flashembed]

Actionscript:

[cc lang=”actionscript”]
//number of balls
var numBalls:uint = 50;
var defaultBallSize:uint = 30;

//init
makeDots();

function makeDots():void {
//create desired number of balls
for (var ballNum:uint=0; ballNum stage.stageWidth) {
thisBall.x = 0 – thisBall.width;
}
else if(thisBall.x < 0 - thisBall.width) { thisBall.x = stage.stageWidth; } if(thisBall.y > stage.stageHeight) {
thisBall.y = 0 – thisBall.height;
}
else if(thisBall.y < 0 - thisBall.height) { thisBall.y = stage.stageHeight; }if (thisBall.scaleX > maxScale){
thisBall.scaleX = thisBall.scaleY = maxScale;
}
else if (thisBall.scaleX < minScale){ thisBall.scaleX = thisBall.scaleY = minScale; } if (thisBall.alpha > maxAlpha){
thisBall.alpha = maxAlpha;
}
else if (thisBall.alpha < minAlpha){ thisBall.alpha = minAlpha; } }function randomColor():Number{ return Math.floor(Math.random() * 16777215); } [/cc]

Source:

as3random_brownian_movement.fla