AS3: Event.SOUND_COMPLETE Event Not Firing
hey everyonehave a look at the attached code. its not very complex but for some reason i can't get the onPlaybackComplete method to fire. any ideas why? SoundClick is an mp3 in the library set to export as an extension of the Sound class. it plays fine, so presumably extending Sound and accessing its methods is working ok, just cant get that sound_complete event to fireAttach Codepackage ccg.gui {import ccg.gui.*;import flash.events.*;import flash.media.*;import flash.utils.*;public class RiderAudio2 {private var _effectGenericClick:SoundClick;public function RiderAudio2 (){trace("RiderAudio INIT");_effectGenericClick = new SoundClick();_effectGenericClick.addEventListener( Event.SOUND_COMPLETE, onPlaybackComplete );_effectGenericClick.play();};public function onPlaybackComplete ( e:Event ):void{trace("RiderAudio onPlaybackComplete ");};};};
Adobe > ActionScript 1 and 2
Posted on: 09/23/2007 11:28:23 AM
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
SOUND_COMPLETE Event Not Firing
so i've an mp3 in the library that extends the Sound class called MusicHiding instantiated thus:
mh = new MusicHiding();
mh.addEventListener( Event.SOUND_COMPLETE, onPlaybackComplete )
mh.play();
elsewhere:
function onPlaybackComplete ( e:Event ):void
{
trace("onPlaybackComplete ")
}
this method never gets called. what could possibly be preventing that?
Event.SOUND_COMPLETE Firing Early
Hi all... I am creating an mp3 player and have ran into an issue with the seek capability of the application. I want to be able to show the progress of the sound playing and allow the user to click on this progress bar to seek through the sound.
The problem arises when I go to seek past 55 or 60% of the sounds length... the Event.SOUND_COMPLETE fires and the onPlaybackComplete function is called, stopping the sound.
I have just begun experimenting with ActionScript, so any criticism is welcome and much appreciated concerning general code organization and how to fix this problem.
First I extend the DataGrid class to change some of it's behavior, such as column resizing. This class loads the dataProvider for the data grid from a MySQL database. When the user double clicks a row, it launches that mp3 file associated with the data.
In onItemDoubleClick, I create a new MyMP3, passing it my container object that has all the buttons and duration bars, etc on it.
So it seeks fine when I click anywhere on the duration_mc's child, squareHit up until about 55% of the length of the song... though the channel.position traces to be at around 55 or 60% of the sound's length, Event.SOUND_COMPLETE fires a few seconds later. Please advise on how to fix this. Thanks.
Attach Code
// MyMP3DataGrid
package
{
// import statements
import fl.controls.dataGridClasses.DataGridColumn;
...
public class MyMP3DataGrid extends DataGrid
{
private var loadDPCount:int = 0;
private var divider:Sprite;
private var variables:URLVariables;
private var request:URLRequest;
private var loader:URLLoader;
private var dataXML:XML;
private var _dataProviderURL:String;
private var dProvider:DataProvider;
private var _stage:Sprite;
private var lastmp3:MyMP3;
public function MyMP3DataGrid( container:Sprite, dataProviderURL:String )
{
super();
_stage = container;
_dataProviderURL = dataProviderURL;
getDataProvider();
doubleClickEnabled = true;
addEventListener( ListEvent.ITEM_DOUBLE_CLICK, onItemDoubleClick );
}
public function drawDivider():void
{
var dProvider:DataProvider = dataProvider;
divider = new Sprite();
divider.graphics.lineStyle(3, 0xFFcc33, 0.6 );
divider.graphics.moveTo(0,0);
divider.graphics.lineTo(0, (( dProvider.length > 18 ) ? rowHeight * 18 : ( dProvider.length + 1 ) * rowHeight ));
divider.visible = false;
}
override protected function handleHeaderResizeDown(event:MouseEvent):void
{
divider.x = event.stageX;
divider.y = this.y;
_stage.addChild(divider);
divider.visible = true;
super.handleHeaderResizeDown(event);
}
override protected function handleHeaderResizeMove(event:MouseEvent):void
{
divider.x = event.stageX;
}
override protected function handleHeaderResizeUp(event:MouseEvent):void
{
divider.visible = false;
var delta:Number = event.stageX - columnStretchStartX;
var newWidth = columnStretchStartWidth + delta;
resizeColumn(columnStretchIndex, newWidth);
super.handleHeaderResizeUp(event);
}
private function onItemDoubleClick( event:ListEvent ):void
{
if( lastmp3 )
lastmp3.cleanUp();
var mp3info:Object = event.item as Object;
var url:String = './library/'+mp3info.Artist+'/'+mp3info.Album+'/'+mp3info.Name;
var mp3:MyMP3 = new MyMP3( _stage, url, mp3info );
lastmp3 = mp3;
_stage.addChild(mp3);
}
public function getDataProvider():void
{
variables = new URLVariables();
variables.action = "getmp3s";
request = new URLRequest();
request.url = _dataProviderURL;
request.method = URLRequestMethod.POST;
request.data = variables;
loader = new URLLoader();
loader.addEventListener( IOErrorEvent.IO_ERROR, loaderIOErrorHandler );
loader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
try
{
loader.load(request);
}
catch (error:Error)
{
// TO DO: Output errors to the user in a user friendly way
trace("Unable to load URL");
}
}
private function loaderIOErrorHandler( event:IOErrorEvent ):void
{
loader.removeEventListener( IOErrorEvent.IO_ERROR, loaderIOErrorHandler );
loadDPCount++;
if( loadDPCount < 5 )
getDataProvider();
else
trace('Server offline of busy.');
}
private function loaderCompleteHandler(event:Event):void
{
loader.removeEventListener( Event.COMPLETE, loaderCompleteHandler );
//trace( event.target.data ); // this will display any php errors from mymp3.php
dataXML = XML(event.target.data);
dProvider = new DataProvider(dataXML);
setSize(770, (( dProvider.length > 17 ) ? rowHeight * 18 : ( dProvider.length + 1 ) * rowHeight ));
dataProvider = dProvider;
drawDivider();
if( !visible )
visible = true;
}
}
}
// MyMP3
package
{
import flash.media.Sound;
import flash.media.SoundLoaderContext;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.net.URLRequest;
import flash.geom.Rectangle;
import flash.events.*;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.utils.Timer;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.display.Sprite;
import flash.display.SimpleButton;
import flash.display.Shape;
import flash.display.DisplayObject;
import fl.controls.Button;
import flash.display.MovieClip;
import flash.display.Stage;
import fl.controls.*;
public class MyMP3 extends Sprite
{
private var posTimer:Timer;
//private var position:Number;
private var durationFormat:TextFormat;
private var format:TextFormat;
private var mp3nameTF:TextField;
private var sndFinished:Boolean;
private var s:Sound;
private var trans:SoundTransform;
private var req:URLRequest;
private var channel:SoundChannel;
private var isPlaying:Boolean;
private var pausePosition:Number;
private var squareHit:Sprite;
private var ctimesec:uint;
private var csec:uint;
private var cmin:uint;
private var chour:uint;
private var csecstr:String;
private var cminstr:String;
private var chourstr:String;
private var estimatedLength:int;
private var playbackPercent:uint;
private var square:Shape;
private var isDragging:Boolean;
private static var mp3playing:Boolean = false;
private var _mp3info:Object;
private var playBtn_btn:flatgreyplay; // = new flatgreyplay();
private var pauseBtn_btn:flatgreypause; // = new flatgreypause();
private var durationTF:TextField;
private var playtimeTF:TextField;
private var duration_mc:DurationBG = new DurationBG();
private var _stage:Sprite;
public function MyMP3( container:Sprite, url:String , mp3info:Object )
{
_stage = container;
//trace( _stage );
_mp3info = mp3info;
BuildUI();
Initialize( url );
SetUpEventListeners();
}
public function cleanUp():void
{
posTimer.removeEventListener(TimerEvent.TIMER, UpdateDurationTF );
playBtn_btn.removeEventListener( MouseEvent.CLICK, Play );
pauseBtn_btn.removeEventListener( MouseEvent.CLICK, Pause );
squareHit.removeEventListener( MouseEvent.CLICK, UpdatePosition );
if( isPlaying )
{
posTimer.stop();
pausePosition = 0;
channel.stop();
isPlaying = false;
pauseBtn_btn.visible = false;
playBtn_btn.visible = true;
removeEventListener( Event.ENTER_FRAME, OnEnterFrame );
mp3playing = false;
}
if( square )
removeChild(square);
durationTF.text = '00:00:00';
var tfFormat:TextFormat = new TextFormat();
tfFormat.size = 10;
tfFormat.color = 0xffffff;
tfFormat.font = "Arial";
durationTF.setTextFormat( tfFormat );
}
private function Initialize( url:String )
{
playtimeTF.text = _mp3info.Time;
var tfFormat:TextFormat = new TextFormat();
tfFormat.size = 10;
tfFormat.color = 0xffffff;
tfFormat.font = "Arial";
playtimeTF.setTextFormat( tfFormat );
posTimer = new Timer(50);
sndFinished = false;
trans = new SoundTransform(1, 0);
s = new Sound();
s.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
channel = new SoundChannel();
req = new URLRequest( url );
s.load(req);
isPlaying = false;
pausePosition = 0;
pauseBtn_btn.visible = false;
isDragging = false;
}
private function ioErrorHandler( event:IOErrorEvent ):void
{
trace( event );
}
private function SetUpEventListeners()
{
posTimer.addEventListener(TimerEvent.TIMER, UpdateDurationTF );
playBtn_btn.addEventListener( MouseEvent.CLICK, Play );
pauseBtn_btn.addEventListener( MouseEvent.CLICK, Pause );
//channel.addEventListener(Event.SOUND_COMPLETE, OnPlaybackComplete);
squareHit.addEventListener( MouseEvent.CLICK, UpdatePosition );
var mevent:MouseEvent = new MouseEvent( MouseEvent.CLICK );
playBtn_btn.dispatchEvent( mevent );
}
public function Play(e:MouseEvent)
{
if( !isPlaying && !mp3playing )
{
posTimer.start();
channel = s.play(pausePosition, 0, trans);
if( !channel.hasEventListener(Event.SOUND_COMPLETE))
channel.addEventListener(Event.SOUND_COMPLETE, OnPlaybackComplete);
isPlaying = true;
playBtn_btn.visible = false;
pauseBtn_btn.visible = true;
if( !squareHit.hasEventListener(MouseEvent.CLICK ))
squareHit.addEventListener( MouseEvent.CLICK, UpdatePosition );
addEventListener(Event.ENTER_FRAME, OnEnterFrame);
mp3playing = true;
}
}
private function Pause( e:MouseEvent )
{
if( isPlaying )
{
posTimer.stop();
pausePosition = channel.position;
channel.stop();
isPlaying = false;
pauseBtn_btn.visible = false;
playBtn_btn.visible = true;
removeEventListener( Event.ENTER_FRAME, OnEnterFrame );
mp3playing = false;
}
}
private function OnPlaybackComplete( e:Event )
{
trace( 'onplaybackcomplete' );
posTimer.stop();
isPlaying = false;
pausePosition = 0;
pauseBtn_btn.visible = false;
playBtn_btn.visible = true;
removeChild( square );
square = new Shape();
square.graphics.beginFill(0xFFCC33, 0.5);
square.graphics.drawRect( 0, 0, duration_mc.width, duration_mc.height );
square.graphics.endFill();
square.x = duration_mc.x;
square.y = duration_mc.y;
//square.addEventListener(MouseEvent.CLICK, UpdatePosition);
addChild(square);
removeEventListener( Event.ENTER_FRAME, OnEnterFrame );
channel.removeEventListener(Event.SOUND_COMPLETE, OnPlaybackComplete );
//removeChild(square);
durationTF.text = '00:00:00';
var tfFormat:TextFormat = new TextFormat();
tfFormat.size = 10;
tfFormat.color = 0xffffff;
tfFormat.font = "Arial";
durationTF.setTextFormat( tfFormat );
mp3playing = false;
}
private function UpdatePosition( e:MouseEvent )
{
//trace( squareHit.width, e.localX );
var position:Number = Math.ceil(s.length / (s.bytesLoaded / s.bytesTotal)) * ( e.localX / squareHit.width );
//trace( channel.position, s.length );
//if( position < s.length )
//{
if( isPlaying )
{
channel.stop();
channel = s.play(position, 0, trans);
if( !channel.hasEventListener(Event.SOUND_COMPLETE))
channel.addEventListener(Event.SOUND_COMPLETE, OnPlaybackComplete);
}
else if( !mp3playing )
{
posTimer.start();
channel = s.play(position, 0, trans);
if( !channel.hasEventListener(Event.SOUND_COMPLETE))
channel.addEventListener(Event.SOUND_COMPLETE, OnPlaybackComplete);
isPlaying = true;
playBtn_btn.visible = false;
pauseBtn_btn.visible = true;
if( !squareHit.hasEventListener(MouseEvent.CLICK ))
squareHit.addEventListener( MouseEvent.CLICK, UpdatePosition );
addEventListener(Event.ENTER_FRAME, OnEnterFrame);
mp3playing = true;
}
//}
}
private function OnEnterFrame( e:Event )
{
estimatedLength = Math.ceil(s.length / (s.bytesLoaded / s.bytesTotal));
playbackPercent = Math.round(100 * (channel.position / estimatedLength));
if( square && square.parent == this )
{
//square.removeEventListener( MouseEvent.CLICK, UpdatePosition );
removeChild( square );
}
square = new Shape();
square.graphics.beginFill(0xFFCC33, 0.5);
square.graphics.drawRect( duration_mc.x, duration_mc.y, ( playbackPercent / 100 ) * ( squareHit.width), squareHit.height );
square.graphics.endFill();
//square.addEventListener( MouseEvent.CLICK, UpdatePosition );
addChild(square);
}
private function BuildUI()
{
// play button
playBtn_btn = _stage.getChildByName('playBtn_btn') as flatgreyplay;
// pause button
pauseBtn_btn = _stage.getChildByName('pauseBtn_btn') as flatgreypause;
// volume bar
/*volumeBarBtn = CreateVolumeBar();
volumeBarBtn.x = playBtn.width + 3;
volumeBarBtn.y = 0;
this.addChild(volumeBarBtn);*/
// duration textfield
durationTF = _stage.getChildByName('durationTF') as TextField;
// duration_mc
duration_mc = _stage.getChildByName('duration_mc') as Slider;
// playtime textfield
playtimeTF = _stage.getChildByName('playtimeTF') as TextField;
// mp3 name textfield
mp3nameTF = _stage.getChildByName('mp3nameTF') as TextField;
mp3nameTF.text = _mp3info.Name;
var nFormat:TextFormat = new TextFormat();
nFormat.font = "Arial";
nFormat.color = 0xffffff;
nFormat.size = 12;
nFormat.bold = true;
mp3nameTF.setTextFormat(nFormat);
// mp3 position hit area
squareHit = new Sprite();
squareHit.graphics.beginFill(0x000000, 0);
squareHit.graphics.drawRect( 0, 0, duration_mc.width, duration_mc.height);
squareHit.graphics.endFill();
squareHit.buttonMode = true;
squareHit.x = duration_mc.x;
squareHit.y = duration_mc.y;
addChild(squareHit);
}
private function UpdateDurationTF(e:TimerEvent)
{
ctimesec = Math.floor( channel.position / 1000 );
chour = Math.floor( ctimesec / 60 / 60 );
if( chour < 10 ) chourstr = '0' + chour;
else chourstr = chour.toString(10);
cmin = Math.floor(ctimesec / 60);
if( cmin < 10 ) cminstr = '0' + cmin;
else cminstr = cmin.toString(10);
csec = Math.floor( ctimesec % 60);
if( csec < 10 ) csecstr = '0' + csec;
else csecstr = csec.toString(10);
durationTF.text = chourstr + ':' + cminstr + ':' + csecstr;
var tfFormat:TextFormat = new TextFormat();
tfFormat.size = 10;
tfFormat.color = 0xffffff;
tfFormat.font = "Arial";
durationTF.setTextFormat( tfFormat );
}
}
}
Looping Mp3 File And Event.SOUND_COMPLETE
Dear all,
I am trying to find a workaround to the problem of looping mp3 files, basically the silence in the transition (from end to start). I could use wav files but I need to load the file externally, which makes not possible to use wav. So I did this
HTML Code:
var channel:SoundChannel = myMp3.play();
channel. addEventListener (Event.SOUND_COMPLETE, onComplete);
function onComplete(event:Event){
channel = assets.sounds.piston.play();
}
Then after some time a use this code to stop and remove the listener:
HTML Code:
channel.stop();
channel.removeEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
However the problem is still there
Edit: Now I know it is not a problem of flash, it is problem of the mp3 format itself. Any way, is there a workaround?
Thanks in advance
Event.ID3 Not Firing And I Don't Know Why?
Hi all,
I can't seem to figure out why my ID3 event isn't firing when I'm loading in MP3s. I know that the MP3 files have the metadata V2. The MP3 files are getting loaded via Javascript through ExternalInterface - everything works, except there's no ID3 event.
Thanks to anyone who can shed some light on what I'm doing wrong.
Here's a link to the page with working OPEN, PROGRESS, COMPLETE events:
http://video.psandl.com/u/
And here's the code:
Code:
import flash.external.ExternalInterface;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.events.IOErrorEvent;
import fl.video.FLVPlayback;
import flash.media.Sound;
import flash.media.ID3Info;
import flash.text.TextField;
var audioDir:String = "aud/";
var videoDir:String = "vid/";
var loadStarted:Boolean = false;
var slc:SoundLoaderContext = new SoundLoaderContext(3000);
//::: CREATE TEXTFIELD
displayTextField.x = 157;
displayTextField.y = 30;
displayTextField.height = 60;
displayTextField.width = 400;
displayTextField.text = "Now Playing:";
var displayTextFormat:TextFormat = new TextFormat();
displayTextFormat.size = 12;
displayTextFormat.color = 0x7b7e61;
displayTextField.defaultTextFormat = displayTextFormat;
//::: EVENT HANDLERS
function onOpenMP3(e:Event):void
{
displayTextField.text = "Opening...";
}
function onLoadingProgress(e:ProgressEvent):void
{
if (!loadStarted)
{
displayTextField.appendText("
Loading Progress...");
loadStarted = true;
}
}
function onPlaybackComplete(e:Event):void
{
displayTextField.appendText("
Playback Complete");
}
function onIOError(e:IOErrorEvent):void
{
displayTextField.appendText("
ERROR opening file!");
}
function id3Handler(e:Event):void
{
displayTextField.appendText("
Received ID3 Data:");
var id3:ID3Info = e.target.id3;
for (var propName:String in id3)
{
displayTextField.appendText("
" + (propName + " = " + id3[propName]));
}
//var id3:ID3Info = s.id3;
//displayTextField.text = "SONG: " + s.id3.songName + "
ARTIST: " + s.id3.artist;
}
//::: RECEIVE DATA FROM JAVASCRIPT
function getTextFromJavaScript(str:String):void
{
SoundMixer.stopAll();
loadStarted = false;
//displayTextField.text = "From JavaScript:
Loading..." + str;
//flv_pb.play(videoDir + str);
var s:Sound = new Sound();
s.addEventListener(Event.ID3, id3Handler);
s.addEventListener(Event.OPEN, onOpenMP3);
s.addEventListener(ProgressEvent.PROGRESS, onLoadingProgress);
s.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
s.load(new URLRequest(audioDir + str),slc);
var sc:SoundChannel = s.play();
sc.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
}
ExternalInterface.addCallback("sendTextToFlash", getTextFromJavaScript);
Function Firing Without Event
Hi,
I wanted to get a clip event to fire a function.
I have written the function to be called & then get the clips "onPress" event to fire it sending along a parameter to be traced out.
Problem I've got is that the function fires as soon as the movie opens - without being called. This only happens when I include a parameter.
Anyone any ideas?
fla attached - code below.
code: stop();
function echoit(some) {
this._x += 10;
trace(some);
}
_root.some_mc.onRelease=echoit("moved!");
OnMouseWheel Event Not Firing?
Hi everyone,
I'm a bit stumped by this one especially since I have not read similar posts in these forums. Essentially, the onMouseWheel event doesn't seem to work at all.
I've tried creating the listener on a clip, an object, and a class without any luck. I've tried numerous examples to see if there may be a tidbit I've been missing and they also don't work. Samples of onMouseWheel listeners online (SWFs demonstrating the outcome) also don't respond. I've also tried it under a variety of browsers as well as the standalone Flash player.
I wouldn't consider myself a noob when it comes to Flash; I've been a professional Actionscript developer for over 5 years now and I feel that I have a pretty good grasp on the language. I also work with two other talented developers who I think are tops when in comes to AS and Flash in general. They also can't get any onMouseWheel events going (yes, we're all working on PCs). I'm curious as to why I haven't been able to get this relatively simple listener going. I've tried it on my work and home computers with different copies of the Flash authoring environment. I've also tried to get the mouse wheel to work at friends homes as well as when I was up at my folks place and NO MOUSE WHEEL!
Is this a cruel joke of some sort? I can't believe that three AS developers working on three machines couldn't get it to work. I'm also stunned that trying it on roughly 5 different PCs of different makes and models with varying hardware/software also failed to produce any results. Simply put, I haven't seen the mouse whel listener working in Flash and I've been trying it on and off since MX.
Does anyone out there have an explanation of what may be going on? Am I cursed? Has anyone else encountered this problem? I am willing to try any and all suggestions you may have.
Many humble thanks,
Patrick
Event Firing Order?
What is the event firing order for startup/shutdown of a Flash file? Also, what is the firing order when an object is added to and deleted from the stage?
For some reason I cannot track this info down anywhere, and a link to Adobe reference would be preferred, if it exists.
Added Event Is Not Firing
I have a simple event that never fires. I have gone through the help section and the syntax appears to be correct but I am new to 3.0 so perhaps I am missing something obvious that someone here can help me with. The loader just loads a jpg and I'm trying to add an init event to it. What is really confusing is that the loader loads the jpg with no problems but the init event never fires which leads me to think it's either something with my declaration of the event or possibly even a sandbox issue but the image loads so I don't know if that's possible. Here's the code for the listener if anyone can help.
Attach Code
var mylv4:Loader = new Loader();
function initHandler(event:Event):void
{
text1.text = "ok";
}
mylv4.addEventListener("INIT", initHandler);
ITEM_ROLL_OVER Event Not Firing
Hi guys ... I am developing an app and trying to implement Dragging Items from one TileList to another. It seems that once I have started dragging a Sprite which has been created from the MOUSE_DOWN event on the source TileList that the destination TileList doesn't receive the ListEvent.ITEM_ROLL_OVER event when I drag the sprite over it. If I offset the sprite so that it doesn't interfere with the mouse pointer, then the ITEM_ROLL_OVER fires.
Any ideas .
Thanks
Event.COMPLETE Not Firing On A Mac
Ran into a strange bug:
I am using the FileReference class in an uploader I created for a CMS. Everything works wonderfully except for one thing: the Event.COMPLETE event is not firing at the end of the upload in Firefox and Safari on a Mac. It works perfectly in all Windows browsers I test (FF, IE7, and Opera), and curiously, it works on another server I have it on in both Mac and PC.
Does anyone have ANY idea why this might be? I know that I can hack it a bit and have the script check for bytesLoaded vs bytesTotal, as a kind of pseudo-event-complete trigger, but I would prefer not to. Thanks to anyone with any info!
Event.COMPLETE Not Firing
Hey all,
I have a simple image loader trying to load an image with an Event Listener.
The COMPLETE event never fires however.
If I use Event.ENTER_FRAME, for example, the image loads in there just fine (but is done so hundreds of times, of course).
Code:
...
private var imageLoader:Loader;
var request:URLRequest;
private function loadImage() {
request = new URLRequest(itemData[itemId][3]);
imageLoader = new Loader();
imageLoader.addEventListener(Event.COMPLETE, imageComplete);
imageLoader.load(request);
}
public function imageComplete(event:Event) {
addChild(imageLoader);
}
...
public const any_help_appreciated:Boolean = true;
Progress Event Not Firing In Browser
Hi folks,
This is a strange question, and I feel dumb for asking it - but I've nearly thrown my monitor off the balcony a few times today... here's the problem.
Photo Gallery - I load pics down from a web service into a Loader component. Nice, works great. Between the loads, I have a little Dynamic Text (or Label Component... whatever) that displays "Loading: 50% (5k of 10k)", which is updated in the Loader component's "on (progress)" event. It works great, but only when I'm inside the Flash environment (oh, Flash 8, btw). Once I upload it to the web, it does strange things. It seems like it the "progress" handler is fired once, then forgets it exists - once the text is updated once, it's stays that way - it's tough to debug, since it works great in the IDE, but not in a browser.
I've also used the "registering an event" (addEventListener("progress", "myFunc")) style, and gives me the same sort of headaches.
If anybody has some time to enlighten me, the swf is at http://www.ludema.org/miniGallery/miniGallery.swf. You'll see the label in the middle doesn't change - sometimes I need to refresh it to even get numbers to show up.
If this sounds familiar to anybody, I'd love to post my messy code for all to peruse to help troubleshoot it. I'm wondering if it's a Flash 9 plug-in versus Flash 8 SWF incompatability...
Thanks for the help in advance!
Loader Event Not Firing - Actionscript 3
Hi,
I have found that Event.COMPLETE doesn't get dispatched in IE 6 or 7 on a PC, but does in Firefox and the Flash authoring environment.
I would like the swf to declare when it has completed loading. The code is below. SImply put it into frame 1 of the main timeline and publish it.
In Flash and Firefox it will say 'Initiated' and 'Completed'. In IE it will just say 'Initiated'.
Could somebody give it a try - it's very confusing.
Thanks.
var debugText:TextField = new TextField()
addChild(debugText)
var onEvent = function (event:Event):void
{
trace(event.type)
debugText.text += event.type + "
"
}
loaderInfo.addEventListener(Event.INIT, onEvent);
loaderInfo.addEventListener(Event.COMPLETE, onEvent);
Event.ADDED_TO_STAGE Firing Inconsistently.
I have a fla which simulates software. to streamline production, i'm using an invisible mc with a baseclass which stops the main timeline when added to the stage and starts it up again when clicked.
The problem is that the ADDED_TO_STAGE event is firing inconsistently, sometimes skipping multiple frames.
It works fine when _myParent.play() is changed to _myParent.nextFrame(), but there are times when there will be tweens or other animations between continue buttons.
Here is the base class:
Code:
package com.whatever.buttons
{
import flash.display.*;
import flash.events.*;
public class ID_ContinueButton extends MovieClip
{
public var isEnabled:Boolean = new Boolean;
public var _myParent:MovieClip;
public function ID_ContinueButton()
{
super();
addEventListener(Event.ADDED_TO_STAGE, initialize);
addEventListener(Event.REMOVED_FROM_STAGE, removed);
addEventListener(MouseEvent.CLICK, clicked)
_myParent = (this.parent as MovieClip);
trace("FRAME: "+_myParent.currentFrame+". ID_ContinueButton constructor.")
}
function initialize(event:Event):void
{
this._myParent.stop();
removeEventListener(Event.ADDED_TO_STAGE, initialize);
trace("FRAME: "+_myParent.currentFrame+". ID_ContinueButton added to stage.");
}
function removed(event:Event):void
{
removeEventListener(Event.REMOVED_FROM_STAGE, removed);
trace("FRAME: "+_myParent.currentFrame+". ID_ContinueButton removed from stage.");
}
function clicked(event:MouseEvent):void
{
_myParent.play();
}
}
}
The fla has 12 frames, each with a button on it with a baseclass of ID_ContinueButton.
And here is the trace output:
Code:
FRAME: 1. ID_ContinueButton constructor.
FRAME: 1. ContinueButton added to stage.
FRAME: 1. ContinueButton removed from stage.
FRAME: 2. ID_ContinueButton constructor.
FRAME: 2. ContinueButton added to stage.
FRAME: 2. ContinueButton removed from stage.
FRAME: 3. ID_ContinueButton constructor.
FRAME: 3. ContinueButton added to stage.
FRAME: 3. ContinueButton removed from stage.
FRAME: 4. ID_ContinueButton constructor.
FRAME: 4. ContinueButton added to stage.
FRAME: 4. ContinueButton removed from stage.
FRAME: 5. ID_ContinueButton constructor.
FRAME: 5. ContinueButton added to stage.
FRAME: 5. ContinueButton removed from stage.
FRAME: 9. ID_ContinueButton constructor.
FRAME: 9. ContinueButton added to stage.
I know this is long, but I wanted to be as detailed as possible. Any help?
? Firing An Event With A Property Change
hallo
i'd like to have a particular event fired each time a property has its value changed by another object on the stage (es. each time a button is clicked, it changes the property value and so the event is fired).
Which manner should i use? thx in advance
Is There Some Way To Create My Own Custom Event Firing Object?
I have CS3. I was wondering if there might be some built-in component or class which can help me launch a series of events to synchronize with a movie. I've considered using FLVPlaybackCaptioning, but I can't seem to get that component to trigger the captioning events without actually rendering them on my movie. I don't want those captions on my movie - I want to perform a variety of customized actions depending on the frame (or current time) of an FLV file. Also (and perhaps more importantly) I need these events to have considerably more data than just a name, some text, and a duration. I also need parameters like x, y, height, width, etc which I expect to define in XML or some other structured data object.
Is there some easy way to do this? I've considered parsing all of my XML at first and creating a series of timers, HOWEVER I'm not sure this will work because someone might pause the movie in which case I'd have to cancel all those timeouts and recreate them all when the movie starts.
In the meantime, the FLVPlaybackCaptioning thing is *almost* exactly what I need but not quite. As I mentioned before, I can't find a way to get the FLVPlaybackCaptioning events to fire without the captioning object molesting my FLVPlayback with its ugly captions.
Loader Class Not Firing Event.COMPLETE
I'm having a problem that's got me stuck in AS3. I have this seemingly simple code:
PHP Code:
var loader:Loader = new Loader();
loader.addEventListener(Event.COMPLETE, function(event:Event):void{
trace('hi');
});
loader.load(new URLRequest('photo.jpg'));
The event.complete is never firing. Nothing I do works. If I make it a URLLoader and not a regular Loader it goes through fine and the event is fired, however this is an image I need to add to the stage so I need to use a Loader. But I can't figure out for the life of me why the event.complete isn't firing. I know it's loading because I can add the loader to the stage and the image shows up. Doesn't matter if I do local images or images from a server. What's going on here?
Loader Class Not Firing COMPLETE Event
Hello hello,
So I've got a bit of a problem that is absolutely puzzling me.
I've got a custom Thumbnail class that reads in an image path, a label, and an index. The class simply loads the image and and onComplete it pulls the bitmap out of loader.content, assigns it to a public variable and then dispatches an event saying its completed.
I use these thumbnails in a thumbnail gallery and I don't build the gallery in until all thumbnails are loaded and ready. The problem is the COMPLETE event doesn't always fire for every thumbnail, therefore not allowing the gallery to build.
I used a ProgressEvent.PROGRESS to make sure the files were being loaded, and found that when the loads failed the loader still loaded the totalBytes.
I've also tried Event.INIT and its the same issue.
INIT and COMPLETE just don't seem to be either caught or dispatched.
If anyone is familiar with a problem like this I'd appreciate any help that you could provide.
Thanks in advance.
Code:
public class Thumbnail extends Sprite
{
/******************************************************************************************
* VARIABLES
*****************************************************************************************/
public var label: String;
public var link: String;
public var imagePath: String;
public var index: int;
protected var image: Bitmap;
protected var loader: Loader;
/******************************************************************************************
* CONSTRUCTOR
*****************************************************************************************/
public function Thumbnail(p_imagePath: String, p_label: String = "", p_index: int = 0)
{
//init variables
imagePath = p_imagePath;
label = p_label;
index = p_index;
//setup the loader and the onComplete
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, onLoadComplete, false, 0, true);
loader.load(new URLRequest(imagePath));
}
/******************************************************************************************
* DECONSTRUCTOR
*****************************************************************************************/
public function destroy():void
{
loader = null;
}
/******************************************************************************************
* EVENT HANDLERS
*****************************************************************************************/
/**
* Handles the loader event when the image loading is done
**/
private function onLoadComplete(evt: Event):void
{
image = Bitmap(loader.content);
addChild(image);
dispatchEvent(new Event(Event.COMPLETE));
}
}
Preloader Complete Event Firing Too Early
Hello guys,
I am currently building a preloader for my movie and have the following code:
ActionScript Code:
var websiteLoader:LoaderInfo = this.loaderInfo;websiteLoader.addEventListener(ProgressEvent.PROGRESS, loaderProgressHandler);websiteLoader.addEventListener(Event.COMPLETE, onLoaderComplete);function loaderProgressHandler(event:ProgressEvent):void{ //When loading var loaderBar:MovieClip = loaderbar_mc; var loaderMask:MovieClip = loadermask_mc; var loadedPercentage:int = (Math.ceil(event.bytesLoaded / event.bytesTotal)); loaderBar.x = (loadedPercentage*loaderMask.width) + loaderMask.x; } function onLoaderComplete():void{ trace("completed"); //When loading completes websiteloader_mc.play(); websiteLoader.removeEventListener(ProgressEvent.PROGRESS, loaderProgressHandler); websiteLoader.removeEventListener(Event.COMPLETE, onLoaderComplete);}
On the first frame, I have the preloader assets. On the second frame, assets that are exported for actionscript but set to not export at first frame. On the third frame, I have the actual website.
Now the issue is this, people testing it over internet connections and me testing it flash with simulate download will see the following issue:
The movie will load, COMPLETE will fire causing the movie to play. But the movie hasn't fully loaded yet, so it will play frame 2 when it should play frame 3. Various testing has shown that the movie has not fully loaded yet, but tracing bytesLoaded will show that it is equal to bytesTotal.
Any ideas appreciated
Event Listener Firing Before At Proper Frame, How To Stall?
well, at least i think that is what is happening. i decided to pause my flash lesson by going to a "pause" frame and a button on said frame will then return me to the previous frame i was on. the problem i was having was that the movieclip button was no available to add event listener to even though i set that after the code which switched frames. so i added an event listener that would call a function when when the enter frame event happened, that allows it to work for a few clicks but it returns errors and it eventually returns me to the beginning of the lesson, so thats not good. all info is below. thanks ahead of time to anyone who helps, i'm guessing its something a newbie like me overlooked or didn't understand correctly.
error when i press the pause button:
Code:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at lesson::PauseAll/::activateContinue()
error when i press the continue button:
Code:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at lesson::PauseAll/::activatePause()[/
code on timeline:
Code:
stop();
import lesson.SoundMain;
import lesson.PauseAll;
if (!mySoundMain) {
var mySoundMain:SoundMain = new SoundMain(this);
}
mySoundMain.playNewSound("SU01.mp3");
var pauseAll:PauseAll = new PauseAll(this);
code in PauseAll class:
Code:
package lesson
{
import flash.display.MovieClip;
import flash.events.*;
public class PauseAll
{
private static var holdFrame:int;
public function PauseAll(controlledMovieClip:MovieClip)
{
parentReference = controlledMovieClip;
parentReference.mcPause.addEventListener(MouseEvent.CLICK, pauseAll);
parentReference.mcPause.buttonMode = true;
}
private function pauseAll(e:MouseEvent):void
{
holdFrame = parentReference.currentFrame;
parentReference.mcPause.removeEventListener(MouseEvent.CLICK, pauseAll);
parentReference.mcPause.buttonMode = false;
parentReference.addEventListener(Event.ENTER_FRAME, activateContinue);
parentReference.gotoAndPlay(parentReference.totalFrames);
}
private function continueAll(e:MouseEvent):void
{
parentReference.mcContinue.removeEventListener(MouseEvent.CLICK, continueAll);
parentReference.mcContinue.buttonMode = false;
parentReference.addEventListener(Event.ENTER_FRAME, activatePause);
parentReference.gotoAndPlay(holdFrame);
}
private function activateContinue(e:Event)
{
parentReference.mcContinue.addEventListener(MouseEvent.CLICK, continueAll);
parentReference.mcContinue.buttonMode = true;
}
private function activatePause(e:Event)
{
parentReference.mcPause.addEventListener(MouseEvent.CLICK, pauseAll);
parentReference.mcPause.buttonMode = true;
}
}
}
Firing OnRollOver Event For Children Movieclips From A Parent MovieClip
Dear Friends,
I have several MovieClips who have a single parent movieClip. Now For a rollOver event in the parent, I want to fire the onRollOver event of children also.
Is There a way of firing onRollOver other than rolling the mouse over the movieclip i.e by changing the value of some property or sth.
Cheers,
rohit
MediaDisplay "complete" Event Firing Early.
I've got a MediaDisplay object in my project that seems to be working fine, until I pause and the re-start the playing. When I restart the playing, the "complete" event fires immediately, only I know I'm not at the end of my .flv.
m_listener.complete = function (p_event_obj){
trace("complete: " + p_event_obj.target.totalTime + " " + p_event_obj.target.playheadTime);
};
clip_movie.addEventListener("complete",m_listener) ;
In the trace window I'm getting "complete: 6.734 1.358", so I'm sure I'm not at the end.
Anyone know why this might be happening? I'm working with the previous developer's code, so I'm still wading my way through it, but maybe there's a way to force an event to trigger artificially? I don't know of a way, but it was another idea.
thanks in advance.
Bebeth
PopupManager Not Firing "complete" Event
The following code works in "test movie" mode.
But when I publish and view online it works about half the time.
My cancel button does not have a listener associated and the delete button is visible.
Does anyone see a problem with what I am doing?
var myWindow = mx.managers.PopUpManager.createPopUp(_root, mx.containers.Window, true);
var myWindowListener:Object = new Object();
myWindowListener.complete = function()
{
modalWindow = myWindow.content;
modalWindow.btnCancel.addEventListener("click", myWindowListener);
modalWindow.btn_Delete.visible=false;
}
myWindow.addEventListener("complete", myWindowListener);
PopupManager Not Firing "complete" Event
PopupManager not firing "complete" event
The following code works in "test movie" mode.
But when I publish and view online it works about half the time.
My cancel button does not have a listener associated and the delete button is visible.
Does anyone see a problem with what I am doing?
var myWindow = mx.managers.PopUpManager.createPopUp(_root, mx.containers.Window, true);
var myWindowListener:Object = new Object();
myWindowListener.complete = function()
{
modalWindow = myWindow.content;
modalWindow.btnCancel.addEventListener("click", myWindowListener);
modalWindow.btn_Delete.visible=false;
}
myWindow.addEventListener("complete", myWindowListener);
MovieClipLoader OnLoadInit Event AND Loader Component Complete Event
What´s the difference beetwen the Loader complete event and MovieClipLoader onLoadInit. The manual says onLoadInit is called after the code on the first frame of the loaded clip gets executed, so, it´s better to use onLoadInit if you want to manipulate the loaded asset via code.
So, if anyone could clarify the following points to me, I would be grateful!
- Does the complete event of the Loader component have the same behaviour?
- How does MovieClipLoader knows that the code on the first frame of the loaded assets got executed?
Thanks,
Marcelo.
Custom Event Handlers - Triggering Event Listeners On Other Objects
I'm trying to update an object whenever something happens in another object. At the moment, I have the second object explicitly calling an update function on the first object, but this seems a little sloppy and it strikes me that this is the sort of scenario where I should be using custom event handlers.
I'm not quite sure how they work though. My first assumption is that if I built two objects, one like this which fires off an event:
Code:
public class eventFirer extends Sprite
{
public function eventFirer():void
{
dispatchEvent(new Event("customEvent"));
}
}
...and one like this which updates whenever the custom event happens:
Code:
public class eventListener extends Sprite
{
public function eventListener():void
{
trace ("main");
addEventListener("customEvent", eventFired);
}
private function eventFired(e:Event):void
{
trace ("ok");
}
}
...then eventListener.eventFired would automatically be set off whenever a new eventFirer is created. This seems not to be the case though.
Can anybody enlighten me as to how custom events bubble between otherwise unrelated objects?
Passing Parameters From Event Listener To Event Handler
Hi Chaps,
First of all, apologies as I know this question has been asked before, but I have spent the last twenty minutes reading this thread and still can't seem to figure out how to apply it to my situation - probably because I'm thick!
I have a number of objects which need to be rotated according to different parameters. I have a function which takes those parameters, then uses the tween class to handle the rotation. I'm then using the tweenEvent class to check for when the motion is complete. Then, I need access to those same parameters in the complete handler to do further operations. The problem I have is that the tween event class doesn't allow me to pass the parameters along to the cpmpleteHandler, so I'm stuck getting my parameters from the first function to the second function:
Code:
function rotate(parameters){
rotationTween = new Tween(object,parameter1,parameter2,........);
rotationTween.addEventListener(TweenEvent.MOTION_FINISH,completeHandler);
}
function completeHandler(e:TweenEvent){
//need access to the paremeters passed into the first function here!!
}
From reading the thread mentioned above, I have a feeling I may need a custom class to do this - please don't laugh but I've never written (or had the need to) write my own class before, so I really wouldn't know what to do. Any help greatly appreciated, but an actual code snippet which demonstrates this would be even better!
Ric.
Event Listener Mouse Event Click - Obstructions
This is an oversimplification of my problem.
I have an event listener on a sprite.
I then have portions of this sprite covered with other sprites or moveclips.
If I click a movieclip, it blocks my eventlistener on the sprite underneath it.
Is it possible to listen to the even click 'through' a movieclip. I dont want interaction with them, but I dont want them as bitmap data onto the base sprite either...
I Don't Understand The Keywords: This, Event.target, Event.currentTarget
I am almost a complete beginner to Actionscript 3.0.
I've been looking at tutorials and I now understand most of the basic principles and methods of this programing language (creating basic functions ect..).
However I do not understand the following keywords.
1. this
2. event.target
3. event.currentTarget
What do these words refer to?
How are they different from each-other?
When must i use them?
Event Propagation Vs. Event Blocking -- Confused, Even After Moock
I thought I understood the AS3 event scheme: capture, target, bubbling. That events (e.g. MouseEvents) travel from stage to the object clicked on and then back again, and all objects in the display chain receive and can check that event. But it's also true, it seems, that Interactive Objects in front of others will block and "absorb" events, and those beneath will never hear of the event (unless mouseEnabled for the blocking object is set to false). I don't understand this (seeming) contradiction.
On the Kirupa forums:
Along with event propagation in ActionScript 3 comes different phases of events with display objects. With propagation, you have events being propagated from display objects to other display objects, such as mouse click events being propagated from children to their parents. This lets clicks within children objects to be recognized by parents (since children make up the contents of their parents, its only natural for the parent to also have those same events). The phases of such an event represent the progression of the event as it makes its way through the parent and child objects.
Events actually start with parent objects (phase 1: capturing), starting with the top most parent (stage) and making its way down to the child where the event originated (phase 2: at target). Then after reaching the child it makes its way back up through all the parents again (phase 3: bubbling).
But also:
Though ActionScript 3 now supports event propagation (capturing, bubbling, etc). Events like mouse events still only occur for one specific target for each individual event. In other words, when you click the mouse button over some objects in a Flash movie, only one of those objects is going to recieve the event even though the mouse is physically over other objects as well.…One important thing to keep in mind is that, in ActionScript 3, mouseEnabled is true by default. This means, without any event handlers or listeners used in a movie, every InteractiveObject instance will capture mouse events and prevent them from reaching any other objects beneath them.
Any clarification much appreciated…
The Best Way To Trigger An Event After A Previous Event Has Played.
What would be the best way to trigger an event via button in one movie clip after another event in has played in a different movie clip.
1. Click button in scene 1 on main stage.
2. The background movie (movie2) should scroll the the designated posistion and stop.
3. Then the foreground layer (movie1) should side in over it after the background has scrolled and stop to display information.
Now if you click another button I would like the clip to do this:
1. The foreground layer (movie1) slides back out opposite as it came in.
2. And the the background (movie2) rotates to it's new posistion and stops.
3. The foreground layer slides in same as (movie1) only some other tab and stops.
I'm completely stumped how to do this any help would be greatly appreaciated.
I posted the file here:
http://www.jbowen.com/jbcspage.swf
and
http://www.jbowen.com/jbcspage.fla
If some one could help me out thanks maybe even take a look a the code in the fla document and repost it or explain.
Thanks.
Using An Event Listeners Function At Will - Event Dispatching?
Hi,
I have a event listener that turns a camera on and off according to how much motion there is:
ActionScript Code:
camera1 = Camera.getCamera(""+Number(aCameraComboBoxes[selComboBoxNum].selectedIndex-1));
aCameras[selComboBoxNum].addEventListener(ActivityEvent.ACTIVITY, activityHandler, false, 0, true);
private function activityHandler(event:ActivityEvent):void {
if(event.activating){
//camera is turning on
}else if (!event.activating){
//camera is turning off
}
}
All of this works but I need a way to rerun the addlistener's function without the camera actual turning on or off. Is there a way for me to use this function, and send it the variable it is looking for?
Thanks
Custom Event Handler For A Timer Event?
I understand how to create custom events in order to pass parameters to a function being called by an event listener. I can get this to work fine if the event is being dispatched within my own code. However, I don't get how to do this if the event is a built-in event being dispatched by a Flash object.
Specifically, I need to call a function and pass it parameters when a timer ends. I don't know how to change the information being sent by the Timer because it is a native Flash class rather than something I'm writing. Can someone please clarify how to do this?
Mouse Event, Event.target Vs Movieclip Name
Hi -
Can anyone help me with a mouse event issue, i'm truly baffled. There's a timer event that loads 4 movieclips (named 'serviceType'), each containing an instance of 2 objects (named 'btn' and 'thumbs'). When clicking on the MC (servicetype) it triggers a mouse event. I'm trying to reference child 'thumbs' of the serviceType MC but in the mouse event function, event.target traces no children, but serviceType traces the 2 children. BUT serviceType only refers to the last instance of serviceType that was loaded in the timer event. Why wouldn't event.target work??
Here's the code, and thanks for the help!!
ActionScript Code:
function loadServices(event:TimerEvent):void {
count = event.target.currentCount -1;
serviceType = new MovieClip;
addChild(serviceType);
btn = new Btn(serviceList, count);
thumbs = new ThumbContainer(count);
serviceType.addChild(btn);
serviceType.addChild(thumbs);
serviceType.addEventListener(MouseEvent.CLICK,loadThumbs);
}
function loadThumbs (event:MouseEvent):void {
trace(serviceType.numChildren); /// Displays 2 (but refers to the last instance loaded)
trace(event.target.numChildren);// Displays 0, why??
}
AS 3 Convert Button Event To Key Enter Event
I'm learning how to use regular expressions in ActionScript 3, and can get an input to be tested by regular expressions, and an answer delivered, if a button is clicked after text is entered.
But darn if I can figure how to code it so they just click the enter key after typing what they like. In the following code punk is a button, and there are two text fields, buzzo the input, and tester the answer to the input. The array questo contains the regular expressions, the array anso contains the responses.
I need code to replace the bottom line with a line that relates to key enter being typed. Thanks for any ideas.
Sally
Attach Code
function makeSense(event:MouseEvent):void
{
tester.text="";
var buzz:String = buzzo.text;
buzzo.text="";
for(i=0;i<questo.length;i++){
if(buzz.search(questo[i])!=-1){
tester.text=anso[i];
}
}
}
punk.addEventListener(MouseEvent.CLICK, makeSense);
How To Use SetInterval To Delay Event, Not Just Each Step Of Event
I had some help in setting up this bit of code to fade out a loaded movie:
Code:
function faderFunc() {
_root.holder24._alpha -= 5;
if (_root.holder24._alpha < 0) {
_root.holder24._alpha = 0;
clearInterval(fadeRMS);
}
};
fadeRMS = setInterval(faderFunc, 400);
Trouble is, I am looking to fade the clip slowly to zero once it has been a certain number of seconds, rather than just having the clip fade at a rate of -5 every so many seconds as it is set here.
In comparing this to other code that I have been using setInterval in, I am wondering if the problem is that this setInterval is not control an onEnterFrame event, but rather just control the rate of the alpha fade. I don't see how I could use an on enterFrame with this because the swf has already been loaded into a movie in this same Frame...maybe I am wrong about both of these thoughts, maybe just one.
I would really appreciate some insight on this I have been working with different attempts for a while and cannot get the results I want.
(Here is an example of some other code I am using that does delay the onEnterFrame event, I think, so that the code is not being fully executed until 57 seconds pass...)
Code:
function moveRMS() {
clearInterval(moveRMSInterval);
unloadMovie(_root.holder22);
xstep=(30-holder24._x)/5
ystep =(500-holder24._y)/5
_root.holder24.onEnterFrame = function() {
this._y -= (577-this._y)/ystep;
this._x -= (865-this._x)/xstep;
if (Math.abs(577-this._y)<1 && Math.abs(865-this._x)<1) {
this._y = 577;
this._x = 865;
delete this.onEnterFrame;
}
};
}
moveRMSinterval = setInterval(moveRMS, 57000);
Using An Event Listeners Function At Will - Event Dispatching?
Hi,
I have a event listener that turns a camera on and off according to how much motion there is:
camera1 = Camera.getCamera(""+Number(aCameraComboBoxes[selComboBoxNum].selectedIndex-1));
aCameras[selComboBoxNum].addEventListener(ActivityEvent.ACTIVITY, activityHandler, false, 0, true);
private function activityHandler(event:ActivityEvent):void {
if(event.activating){
//camera is turning on
}else if (!event.activating){
//camera is turning off
}
}
All of this works but I need a way to rerun the addlistener's function without the camera actual turning on or off. Is there a way for me to use this function, and send it the variable it is looking for?
Thanks
How To Use SetInterval To Delay Event, Not Just Each Step Of Event
I had some help in setting up this bit of code to fade out a loaded movie:
Code:
function faderFunc() {
_root.holder24._alpha -= 5;
if (_root.holder24._alpha < 0) {
_root.holder24._alpha = 0;
clearInterval(fadeRMS);
}
};
fadeRMS = setInterval(faderFunc, 400);
Trouble is, I am looking to fade the clip slowly to zero once it has been a certain number of seconds, rather than just having the clip fade at a rate of -5 every so many seconds as it is set here.
In comparing this to other code that I have been using setInterval in, I am wondering if the problem is that this setInterval is not control an onEnterFrame event, but rather just control the rate of the alpha fade. I don't see how I could use an on enterFrame with this because the swf has already been loaded into a movie in this same Frame...maybe I am wrong about both of these thoughts, maybe just one.
I would really appreciate some insight on this I have been working with different attempts for a while and cannot get the results I want.
(Here is an example of some other code I am using that does delay the onEnterFrame event, I think, so that the code is not being fully executed until 57 seconds pass...)
Code:
function moveRMS() {
clearInterval(moveRMSInterval);
unloadMovie(_root.holder22);
xstep=(30-holder24._x)/5
ystep =(500-holder24._y)/5
_root.holder24.onEnterFrame = function() {
this._y -= (577-this._y)/ystep;
this._x -= (865-this._x)/xstep;
if (Math.abs(577-this._y)<1 && Math.abs(865-this._x)<1) {
this._y = 577;
this._x = 865;
delete this.onEnterFrame;
}
};
}
moveRMSinterval = setInterval(moveRMS, 57000);
Using An Event Listeners Function At Will - Event Dispatching?
Hi,
I have a event listener that turns a camera on and off according to how much motion there is:
camera1 = Camera.getCamera(""+Number(aCameraComboBoxes[selComboBoxNum].selectedIndex-1));
aCameras[selComboBoxNum].addEventListener(ActivityEvent.ACTIVITY, activityHandler, false, 0, true);
private function activityHandler(event:ActivityEvent):void {
if(event.activating){
//camera is turning on
}else if (!event.activating){
//camera is turning off
}
}
All of this works but I need a way to rerun the addlistener's function without the camera actual turning on or off. Is there a way for me to use this function, and send it the variable it is looking for?
Thanks
Using Event.target With An Event Handler
Hi folks,
I'm looking for a more efficient way of doing the following:
Code:
function selectLevel():void{
levelSelect.level1.addEventListener(MouseEvent.MOUSE_DOWN,gotoLevel1);
levelSelect.level2.addEventListener(MouseEvent.MOUSE_DOWN,gotoLevel2);
levelSelect.level3.addEventListener(MouseEvent.MOUSE_DOWN,gotoLevel3);
}
function gotoLevel1(e:MouseEvent):void {
currentLevel = 1;
//load up level 1
}
function gotoLevel2(e:MouseEvent):void {
currentLevel = 2;
//load up level 2
}
function gotoLevel3(e:MouseEvent):void {
currentLevel = 3;
//load up level 3
}
As you can probably see, I have a movie clip called 'levelSelect' which contains three buttons - level1, level2 and level3. What I'm doing so far, is adding an event listener to each button, and then if any of them are clicked, it activates a different event handler function for each button.
However, as the only difference in the handler functions is the number of the level, and then assume I have 100 levels, this doesn't seem like very efficient coding!
So, how can I make it so that I have just a single event handler function which all the buttons use, and get it to recognise which level button was clicked? Effectively, I'm trying to do this:
Code:
function selectLevel():void{
levelSelect.level1.addEventListener(MouseEvent.MOUSE_DOWN,clickHandler);
levelSelect.level2.addEventListener(MouseEvent.MOUSE_DOWN,clickHandler);
levelSelect.level3.addEventListener(MouseEvent.MOUSE_DOWN,clickHandler);
}
function clickHandler(e:MouseEvent):void {
//somehow detect the level number 'n' from the instance name of the button, or the child number of the parent movieclip
currentLevel = 'n';
//load up level 'n'
}
I'm sure it has something to do with e.target, or e.currentTarget, but I can't get further than that!
Cheers,
Ric.
[CS3] Dispatching An Event From Inside An Event
Does anyone know how to dispatch an event from inside another event?
I get crazy! I have tried a hundred ways to dispatch an event from inside a onLoad event when loading a XML-file. It just doesn't work!!
Here is a simple example:
Code:
class myClass {
public var xmlData;
public var addEventListener:Function;
public var removeEventListener:Function;
public var dispatchEvent:Function;
function myClass() {
xmlData = new XML();
EventDispatcher.initialize(this);
}
function loadXML() {
xmlData.onLoad = function(success) {
if(success){
trace("success");
sendEventLoaded();
}
else trace("Error: Xml not loaded");
}
xmlData.load("filename.xml");
xmlData.ignoreWhite = true;
}
public function sendEventLoaded() { // send the Event
trace("sendEventLoaded()");
dispatchEvent({target:this, type:"isLoaded"});
}
}
The first issue is not dispatching the event itself, but calling the function sendEventLoaded(). It's like it can't be found from within the onLoad event. When the onLoad event occurs, the text "success" is traced, and but the text "sendEventLoaded()" is never executed!!
Does anyone know how to call the sendEventLoaded() from within the onLoad event? Or is there any other way to do this?
I'm thankful for any help I can get!!
Event.COMPLETE Or Event.INIT
I'm working with the loader class. I have a SWF that's loading a presentation in another SWF. The loader swf has a progress bar and perecentage text field. I want the presentation to start playing ONLY when it's 100% loaded. As of now, it starts playing at 10 - 11%.
Here's the code:
ActionScript Code:
var swf:String = "ips_test.swf";
var myURL:URLRequest = new URLRequest(swf);
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.OPEN, initialize);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, inProgress);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completed);
loader.contentLoaderInfo.addEventListener(Event.INIT, initListener);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorListener);
loader.load(myURL);
function initialize(event:Event):void {
preloader_mc.visible = true;
}
function inProgress(e:ProgressEvent):void {
var percentage:uint = (e.bytesLoaded/e.bytesTotal)*100;
preloader_mc.loader_txt.text = percentage.toString() + "%";
preloader_mc.pbar.scaleX = percentage/100;
}
function completed(event:Event):void {
if(loader.contentLoaderInfo.bytesLoaded == loader.contentLoaderInfo.bytesTotal) {
removeEventListener(Event.OPEN, initialize);
removeEventListener(ProgressEvent.PROGRESS, inProgress);
addChild(loader);
}
preloader_mc.visible = false;
}
function initListener(e:Event):void {
MovieClip(loader.content).play();
}
function ioErrorListener(e:IOErrorEvent):void {
preloader_mc.loader_txt.text = "ERROR";
}
Should I start playing the content of the loader on the INIT or COMPLETE function?
EDIT
Please put code in [ as ] [ /as ] tags (without spaces)
Mouse Event Add Event Listener?
sorry, could not think of a better title!
anyway,
I downloaded a class that perfectly works for me,
it's basically a cube that rotates depending on mouse movement,
the way it does it is with the following line:
spBoard.addEventListener(MouseEvent.MOUSE_MOVE,boa rdMove);
what this does is, whenever the mouse moves the cube moves
the boardMove function does the movement based on the mouse's current position
but what i want to do is the keep the cube moving, if the mouse is on its left, it keeps rotating left, and on its rght, keep rotating right...and preferably to have the speed increase/decrease depending on how far/close mouse is to the center of the cube
any suggestions?
firstly is there an event listener that keeps calling the function just for the mouse 'being there' ? i tried rollover, didn't work
or maybe the boardMove function should be modified? i have no idea how though, totally new to AS3, here's the boardMove function for refrence:
ActionScript Code:
private function boardMove(e:MouseEvent):void {
var locX:Number=prevX;
if(doRotate){
prevX=spBoard.mouseX;
curTheta+=(prevX-locX);
renderView(curTheta);
e.updateAfterEvent();
}
}
Event Listeners VS Event Functions
I'm working on a new project at work where there's lots of custom objects with lots and lots of event listeners. I keep finding myself saying, "why didn't they just use the built in objects with built in event handling?". However, from what I can see it seems like AS3 leans heavily towards using Event Listeners as opposed to putting event responsibility on the object itself (E.G. XML.onload). Is there an advantage to this (other than making it more Java like?) I've always favoured keeping the responsibility on the object itself because it seems like one less object to keep track of and also makes things feel more self contained. If I have 10 objects that fire 10 different events, I have to create 10 different event handlers (or 10 different case statements within the same event handler), whereas with self event handling, I just code in the event function.
Anyways, I wanted to open discussion to which method of event handling you prefer and why, and also what you believe the advantages to this. I was searching google for previous discussions on this but I couldn't seem to find anything, so I thought I'd get the ball rolling! Looking forward to reading these, try not to be too elitist in your posts!!
Can You Initialize A Function With A Event Also Without Event?
For example i have this function:
function doSomething(event:MouseEvent):void {
trace("do a lot of coding...");
}
Now if i want to run the same function as above without the 'click event' on your mouse that does
not seem to be possible.
Is there a work around? Or is the best way to make a in between function like this:
function doManyThings() {
trace("a lot of code here..");
}
function doSomething(event:MouseEvent):void {
doManyThings();
}
Event Dispatcher: Only Receives Event Once
Hey all,
So I have two classes talking to each other with EventDispatcher. One is a thumbnail of an image, and when it's clicked, it sends an event to the other class to display the full size version. I'm using a MovieClipLoader instance to load the full version (and the thumbnail).
Here's how it's sending the event from the thumbnail class:
Code:
private function initButton () {
this.loadMe.onPress = function () {
this._parent.sendEvent();
}
}
private function sendEvent () {
// create eventObject to be passed to anything that is listening
var eventObject:Object = {target:this, type:'onPhotoSelected'};
eventObject.photo2load = this.photoID;
trace ("send Event " + eventObject.photo2load);
// dispatch event that tells any listeners to load the full version
dispatchEvent(eventObject);
}
And here's what's receiving the event:
Code:
public function onPhotoSelected (listenObj) {
trace ("event received");
this.loadPhoto(listenObj.photo2load);
}
public function loadPhoto (photoID:Number) {
trace ("photoID " + photoID);
fullImageLoader.loadClip(this._parent.fullImageURL + this._parent.fileNames[photoID] + ".jpg", this);
}
The problem I'm having is it loads the full size version ONCE. After that, it no longer receives the event. The ("event received") trace no longer comes through. But the ("send event") trace continues to work.
The other weird part is if I comment out the loadClip, then the events come through just fine on both sides. But it's like after it loads an image once, it quits responding to that event ('onPhotoSelected'). Is there some kind of mis-communication between the events of the MovieClipLoader and my custom event or something?
Any theories appreciated!
Event Handlers Vs. Event Listeners
I'm having trouble understanding why listeners are necessary, beyond tying events to objects "conceptually." Are listeners used that often? What am I missing?
|