December 23, 2009

Flash and JavaScript

I've been doing some experiments on having a small SWF communicate with JavaScript (and vice versa). Essentially it's a little pop sound that gets triggered on a certain event completion by JavaScript. (Think GTalk in GMail or Facebook chat pop notifications).

I first attempted to have a single frame with an AudioLayer and simply rewind and play the movie each time I needed the notification to sound. Easier said than done. The Flash file would play immediately when it was loaded and (for whatever reason) was not listening to {play: 'false'} that SWFObject was sending it as a parameter. Also, the JavaScript event listener in my ActionScript was not letting me call gotoAndPlay(1); - go to the first frame and play it.

I should mention I know very, very little about ActionScript and Flash in general.

Regardless, I finally changed my approach and started googling referencing a sound file directly in the library, rather than importing it into the frame and replaying the frame.

I found a great page detailing which steps to follow to reference and play a sound directly from a library (the sound is exported when you publish your fla to SWF).

The solution is to "link" the audio file and give it a class identifier. This way, in my ActionScript, I can simply create a new instance of the sound using its identifier and call play() on the class.

Here's my ActionScript - it's all in a AS3 fla, first (and only) frame - that sets up the external interface listener:

import flash.external.ExternalInterface;

function playNotification():void {
 var sound = new NotificationPop();
 sound.play();
}

ExternalInterface.addCallback("playNotification", playNotification);

Here's my JavaScript that I call to trigger the SWF's external interface function declared above. The #notification id in XHTML refers to the tag that SWFObject generates. You simply call your declared external interface callback directly on .
function playNotification()
{
 $('#notification').playNotification();
}
Thanks to republicofcode.com for the tutorial. Check out the full article here.

No comments:

Post a Comment