29 January 2008

Flex 2: Embedding Flash 9 swfs and controling the MainTimeline

I've been embedding Flash 9 swfs into a Flex 2 project using the following code:

[Bindable]
[Embed(source="myFlash9.swf")]
private var mySwf:Class;

This creates the bindable variable "mySwf" which can be bound to the backgroundImage attribute of certain components e.g.

<mx:Canvas backgroundImage="{mySwf}" />

However much I tried, I couldn't access the timeline of that swf as it was cast as a Class type and essentially wasn't a MovieClip. Flex only permits Class or String variables when embedding in this way.

I needed to find a way to load a swf into Flex and use it as a fully accessible MovieClip. Here's what I did:
  • Create a bindable MovieClip variable
  • Load in the swf using the flash.display.Loader class
  • Assign the result from the Loader class to the bindable MovieClip variable
  • used the Image component in Flex to add the swf to the application

Here's the complete MXML code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.net.URLRequest;
import flash.display.MovieClip;
import flash.display.Loader;
import flash.events.*;

[Bindable]
private var mySwf:MovieClip;

private function init():void{
var bgURL:URLRequest = new URLRequest("Test.swf");
var bgLoader:Loader = new Loader();
bgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
bgLoader.load(bgURL);
}

private function completeHandler(event:Event):void {
mySwf = event.target.content as MovieClip;
mySwf.gotoAndPlay(20); // access the timeline of the loaded swf
}

]]>
</mx:Script>

<mx:Canvas width="856" height="527" horizontalCenter="0" verticalCenter="0">
<mx:Image source="{mySwf}" />
</mx:Canvas>
</mx:Application>


You can now directly access the timeline of the loaded swf using the "mySwf" variable.

Using the backgroundImage attribute caused errors as it expected a Class variable to be passed into it. Using Image seems to have got around this problem.

5 comments:

Anonymous said...

is it possible with flash 8 swf?

Anonymous said...

Looks like you lost your embedding capability for the SWF. I have found that you can not touch the timeline of a loaded SWF when it is embedded. Have you found different results?

Thanks,
Jason

Resolver said...

I make loading swf by this method. And load swf from another domain. But nothing happend. Flash movie from domain not loading.
Debugger sais 0 bytes loaded.
Can I make swf movie embeded and provide some parameters(FlashVars) to this movie. I haven't sources and can't add functions to this Movie.

Anonymous said...

Have anyone tried to associate an event listener to a swf symbol.
It seems that no actions could be added.

alecmce said...

I just stumbled across this, looking for blog posts similar to mine:

http://alecmce.com/as3/embed-asset-gotcha

Hope the solution helps someone!