How to skip video if button is not pressed in AS3 Flash? - actionscript-3

I'm working on a video ad self project in AS3. Basically the length of the video is 10 seconds. I have set a timer that on 5 seconds a 'Keep Watching' button will show and if interacted the video will continue playing. And if not, at 7 seconds it will automatically end the video. How do I prompt the video to stop playing if the button is not pressed? I am getting confused.
var baseTimer:Timer = new Timer(5000,1)
var isInteracted:Boolean = false;
baseTimer.addEventListener(TimerEvent.TIMER, testTimer);
btSkip.addEventListener(MouseEvent.CLICK, btSkipvideo);
baseTimer.start();
function btSkipvideo(e:MouseEvent)
{
if (!isInteracted)
{
btSkip.visible = false;
}
else
trace("This is a testing");
}

Just create another timer to accomplish this. So something like this:
var baseTimer:Timer;
var timeoutTimer:Timer;
//assuming your btSkip button is a timeline object that is not currently visible
btSkip.addEventListener(MouseEvent.CLICK, btSkipvideo, false, 0, true);
function startVideo():void {
//do whatever you do to start the video
//create the base timer to show the button after 5 seconds
baseTimer = new Timer(5000, 1);
baseTimer.addEventListener(TimerEvent.TIMER, showBtn, false, 0, true); //use weak listener so the timer doesn't stay in memory forever
baseTimer.start();
}
function endVideo(e:Event = null):void {
//do whatever you do to stop the video
}
function showBtn(e:Event):void {
btSkip.visible = true; //or however you decide to show the button
//at this point it's been 5 seconds since the video started to play
//create the other timer to end the video after 2 additional seconds
timeoutTimer = new Timer(2000, 1);
timeoutTimer.addEventListener(TimerEvent.TIMER, endVideo, false, 0, true);
timeoutTimer.start();
}
function btSkipvideo(e:MouseEvent){
if (timeoutTimer) {
//stop the timer so it doesn't end the video
timeoutTimer.stop();
}
btSkip.visible = false; //or however you'd hide the button
}

At the first, I think that's better to use your video player ( FLVPlayback component, NetStream object, ... ) to get the exact time ( 5 seconds and 7 seconds ) to execute any thing because of the problem of buffering of the stream ... But just to answer your question using a Timer object, I think that you can use only one Timer to do what you are looking for :
var timer:Timer = new Timer(1000); // you can set the repeat count to 7 if you want
timer.addEventListener(TimerEvent.TIMER, on_Timer);
function on_Timer(e:TimerEvent): void {
switch (e.target.currentCount) {
5: // 5 seconds, show the "Keep Watching" button
btSkip.visible = true;
break;
7: // 7 seconds, if the timer is always running, so stop the video
stop_the_video();
break;
}
}
function play_the_video(): void {
// start playing your video
timer.start();
}
function stop_the_video(): void {
// stop playing your video
timer.stop();
}
btSkip.addEventListener(MouseEvent.CLICK, btSkipvideo);
function btSkipvideo(e:MouseEvent): void {
timer.stop();
}
Hope that can help.

Related

Actionscript 3 Control Timeline after Duration of no input from user

can anyone help me with this. I know its something very basic, but I just cant work it out.
What I need is for the timeline gotoandstop at frame 1 after 15 seconds of inactivity.
Basically this is for a directory board so if no one is using it, it will return back to the home screen after a period of inactivity.
Any help would be greatly appreciated.
Thankyou
What you can do, is use a Timer object. Then, whenever the user moves the mouse or clicks or presses a key, reset that timer back to 15 seconds.
On your frame 1, make a timer object:
//create the timer object var
var resetTimer:Timer;
//if it doesn't exist yet, create a new timer object and assign it to that var
if(!resetTimer){
resetTimer = new Timer(15000,1); //tick 1 time with a delay of 15
//listen for the TIMER event (fires when the delay is up)
resetTimer.addEventListener(TimerEvent.TIMER, reset);seconds
}else{
resetTimer.reset(); //if it did previously exist, stop/reset it (for when you revisit frame 1)
}
//go back to the first frame if the timer fires
function reset(e:Event = null):void {
resetTimer.reset(); //reset the timer
gotoAndStop(1); //go to frame 1
}
//LISTEN for various user input type events on stage (globally)
stage.addEventListener(MouseEvent.MOUSE_DOWN, userInput);
stage.addEventListener(MouseEvent.MOUSE_MOVE, userInput);
stage.addEventListener(KeyboardEvent.KEY_DOWN, userInput);
stage.addEventListener(KeyboardEvent.KEY_UP, userInput);
//if there was user input, reset the timer and start it again
function userInput(e:Event = null):void {
resetTimer.reset();
resetTimer.start();
}
The only thing left to do is, when you leave frame 1 and want the timeout to be applicable call resetTimer.start(). Presumably that would be on frame 2.
its possible to simulate it so:
class test extends MovieClip{
public var myTimer:Number;
public var input:TextField;
function test(){
myTimer=0;
input=new TextField();
this.addChild(input);
this.addEventListener(Event.ENTER_FRAME,timer);
input.addEventListener(Event.CHANGE, input_from_user);
}
function timer(ev){
myTimer +=(1/25);//if the frame rate is 25 frame per sconde
if(myTimer ==15){
this.gotoAndStop(1);
this.removeEventListener(Event.ENTER_FRAME,timer);
}
}
function input_from_user(ev){
myTimer =0;
}
}

How to stop a movieClip from playing in Flash CS6 AS3 (with Box2D)

I've spent 14 hours on this problem. This is a basic collision checker that sets a MovieClip animation to play when a collision occurs. The clip is
currentBallObject.clip.
It works. The clips plays. But it repeats over and over.
private function checkCollisions():void
{
var i = balls.length;
while (i--)
{
var currentBallObject = balls[i];
if (currentBallObject.contact)
{
//condition hits ground
if (currentBallObject.ground)
{
currentBallObject.body.SetPosition(new b2Vec2(currentBallObject.startX / PIXELS_TO_METRE, currentBallObject.startY / PIXELS_TO_METRE));
currentBallObject.body.SetLinearVelocity(new b2Vec2(0, 0));
currentBallObject.body.SetAngularVelocity(0);
//currentBallObject.texture.pop();
}
else // it hit player
{
// assign clip texture to current position
currentBallObject.clip.x = currentBallObject.body.GetPosition().x * PIXELS_TO_METRE;
currentBallObject.clip.y = currentBallObject.body.GetPosition().y * PIXELS_TO_METRE;
// whisk old object away
currentBallObject.body.SetPosition(new b2Vec2(currentBallObject.startX / PIXELS_TO_METRE, currentBallObject.startY / PIXELS_TO_METRE));
currentBallObject.body.SetLinearVelocity(new b2Vec2(0, 0));
currentBallObject.body.SetAngularVelocity(0);
currentBallObject.contact = false;
}
}
}
}
I added this code to delete the MovieClip or somehow get rid of it after it has played through once. (42 frames). I also tried to add a frameListener and at least a dozen other suggestions. When I add
stop()
The animation doesn't play. It just loads the last frame. The code I have now is:
private function updateClips():void
{
var i = balls.length;
while (i--)
{
var currentBallObject = balls[i];
if(currentBallObject.clip)
{
var frame:int = currentBallObject.clip.currentFrame;
//trace(currentBallObject.clip.currentFrame);
if(frame == 42)
{
currentBallObject.clip._visible = false;
currentBallObject.clip.removeMovieClip();
currentBallObject.clip.enabled = -1;
}
}
}
}
I've tried counting the frames, putting it a run-once function, a frame exit listener, I am out of ideas. I just want to make a MovieClip run one time through. I also tried putting stop() in the timeline and then the animation didn't play. It just loaded the last frame.
Right now the collisions work but the animations stay on the screen forever, looping forever.
Edit: I got the code by Patrick to run without errors.
I added the event listener with the others like this:
_input = new Input(stage);
...
addEventListener(Event.ENTER_FRAME, oEF);
addEventListener(Event.ENTER_FRAME, update);
time_count.addEventListener(TimerEvent.TIMER, on_time);
time_count.start();
}
And then created a function:
private function oEF(e:Event):void{
var i = balls.length;
while (i--)
{
var currentBallObject = balls[i];
if (currentBallObject.clip.currentFrame >= currentBallObject.clip.totalFrames)
{
currentBallObject.clip.stop();
currentBallObject.clip.removeEventListener(Event.ENTER_FRAME, oEF);
if (currentBallObject.clip.parent) currentBallObject.clip.parent.removeChild(currentBallObject.clip);
}
}
}
But I still get the same problem as any other result. The MovieClip disappears on contact without the animation happening.
Through debugging I've learned more. The value of currentFrame starts off going 1-40 then stays at 40 for the rest of the execution.
So the MovieClip is always on the last frame for every object.
if clip is a MovieClip then you can use clip.totalFrames in an enterframe listener.
function oEF(e:Event):void{
if (this.currentFrame >= this.totalFrames){
this.stop();
this.removeEventListener(Event.ENTER_FRAME, oEF);
if (this.parent) this.parent.removeChild(this);
}
}
this.addEventListener(Event.ENTER_FRAME, oEF);
I figured it out.
if (currentBallObject.clip.currentFrame == currentBallObject.clip.totalFrames)
{
trace("Frame before kill: ", currentBallObject.clip.currentFrame);
currentBallObject.clip.x = 0;
currentBallObject.clip.y = 0;
}
The above block goes right after
var currentBallObject = balls[i];
It checks if the movieClip is on the last frame and then gets rid of the clip by setting clip.x & clip.y to 0. I could find no other way to stop the movie in this particular case.

Need help using a timer in Action Script 3

Alright, so I am fairly new to AS3 and I have a level in my game where you have to stay alive for 45 seconds. If I use a code like (Or if there is a better code, I'll use that one)
var myTimer:Timer = new Timer(1000, 1); // 1 second
myTimer.addEventListener(TimerEvent.TIMER, runOnce);
myTimer.start();
function runOnce(event:TimerEvent):void {
trace("runOnce() called # " + getTimer() + " ms");
}
How can I use this to make my game move to scene 6 if they stay alive for 45 seconds? I also want to display text on the animation that keeps track of how long they've been alive so they know how long they have left. How could I accomplish this?
private var startTime:int;
function startGame() {
// this is called when your game starts
startTime=getTimer();
... // rest of init code
}
function onEnterFrame(e:Event):void {
// main loop, whatever you need to do in here
currentTime=getTimer()-startTime; // here we receive the elapsed time
// pause handling is excluded from this example!!11
if (weAreDead()) {
survivalTime= currentTime;// here
...
} else if (currentTime>45000) {
//advance to scene 6 here
}
}
Set the listener for Event.ENTER_FRAME to onEnterFrame, start the game with setting the stored time, and pwn.
The simplest solution is to go ahead and use the timer, but set the value to 45000 and make sure to keep a reference of the timer or it will be garbage collected. Also, create a separate function which allows you to kill the timer from anywhere if this particular thing ever needs to just "go away" without completing.
public static const DELAY:int = 45;
private var _timer:Timer;
public function setTimer():void
{
_timer = new Timer( DELAY * 1000, 1 );
_timer.addEventListener( TimerEvent.TIMER_COMPLETE, timerCompleteHandler );
_timer.start();
}
private function timerCompleteHandler( event:TimerEvent ):void
{
disposeTimer();
goDoTheThingThatYouNeededToDo();
}
public function disposeTimer():void
{
_timer.stop();
_timer.removeEventListener( TimerEvent.TIMER_COMPLETE, timerCompleteHandler );
_timer = null;
}

action script to add a pause button on a few audio buttons

I am currently using the following code to play audio recordings from the project library.
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.events.MouseEvent;
var sound1:Sound = new audio1();
var sound2:Sound = new audio2();
var mySoundChannel:SoundChannel = new SoundChannel();
function stopSound():void
{
//This stops all sound in the sound channel.
//If there is nothing playing, nothing happens.
mySoundChannel.stop();
}
//In this function, we create an argument that allows us to tell the function
//what sound to we want it to play.
function playSound(soundname:String):void
{
try
{
mySoundChannel = this[soundname].play(0, 0);
}
catch(error:ReferenceError)
{
trace("playSound: That sound name doesn't exist.");
return;
}
}
//Hook up buttons-->
button1.buttonMode = true;
button1.useHandCursor = true;
button2.buttonMode = true;
button2.useHandCursor = true;
button1.addEventListener(MouseEvent.CLICK, button1click);
button2.addEventListener(MouseEvent.CLICK, button2click);
function button1click(evt:Event):void
{
stopSound();
playSound("sound1");
}
function button2click(evt:Event):void
{
stopSound();
playSound("sound2");
}
I need to pause the currently playing audio when a button is clicked. How do I do this?
You will need to do five things to your current code in order to pause and resume the currently playing sound:
Create a variable that stores the name of the currently playing
sound, and a variable to store the pause position of the audio.
Create a pause function.
Create a resume function.
Expand the current playSound and stopSound functions to work with the new variables.
Hook up the button event listener.
Step 1:
var currentSound:String = "";
var pausePosition:Number = 0;
Step 2: We're going to save the current position of the audio in that second variable we just created. We can get the current play position of the audio using the mySoundChannel.position property, which returns a Number value (matching the Number type we gave the pausePosition variable).
function pauseSound():void
{
//If there's a song to pause...
if(currentSound != "")
{
//Get pause position.
pausePosition = mySoundChannel.position;
//Stop the sound directly.
mySoundChannel.stop();
}
}
Note we didn't call stopSound(). There's a good reason for that. We're going to put an extra line of code in that function shortly that we don't want to use in pauseSound().
Step 3: Now we create the function to resume audio. Note this is NOT the same as playSound(). We're telling it to start playing from pausePosition, not from 0 (the beginning of the sound clip).
function resumeSound():void
{
//If there's a song to resume...
if(currentSound != "")
{
//Start playing the current audio from the position we left off at.
mySoundChannel = this[currentSound].play(pausePosition);
}
}
Step 4: Since we're now working with those variables we declared in step 1, we need to adjust how playSound() and stopSound() work.
In playSound(), instead of just passing soundname to the sound channel, we're going to save the soundname to currentSound.
function playSound(soundname:String):void
{
try
{
currentSound = soundname
mySoundChannel = this[currentSound].play(0, 0);
}
catch(error:ReferenceError)
{
trace("playSound: That sound name doesn't exist.");
return;
}
}
In stopSound(), we need to actually clear the currentSound and pausePosition variables when we stop, to ensure that resumeSound doesn't start audio after we've totally stopped it.
function stopSound():void
{
//This stops all sound in the sound channel.
//If there is nothing playing, nothing happens.
mySoundChannel.stop();
//Clear our variables.
currentSound = "";
pausePosition = 0;
}
GOTCHA WARNING: Ordinarily, you can loop audio by passing an integer other than 0 in the second argument (where I have the 5) in the following code:
mySoundChannel = this[currentSound].play(0, 5);
In the above code, the sound would play from the beginning, and repeat five times.
However, if you are starting the audio from any position other than 0, what will actually happen is that the audio will loop at the position you start at, not at the beginning.
That is to say, if you use this code:
mySoundChannel = this[currentSound].play(1000, 5);
The sound will loop five times, but every time the sound starts over in the loop, it will start playing from position 1000, and NOT the beginning of the sound (0).
I hope that answers your question!

music playing over and over in Actionscript 3

Greeting,
I I developed a website using flash with Actionscript 3.
I included a music as a background for the website and the music will loaded when the site loaded.
but the problem that when I click buttons to move between pages(frames) then go and click button_01 the music will play again so I will have music playing more than one time in the background
and the sound_btn will not work any more so even I click sound_btn the music will not stop.
the code I'm using is listed down.
Please advice me what I should modify to not allow the music play more than one time in the background while moving from one page(frame) to another.
Regards,
stop();
//number that is redefined when the pause button is hit
var pausePoint:Number = 0.00;
//a true or false value that is used to check whether the sound is currently playing
var isPlaying:Boolean;
//think of the soundchannel as a speaker system and the sound as an mp3 player
var soundChannel:SoundChannel = new SoundChannel();
var sound:Sound = new Sound(new URLRequest("music.mp3"));
//you should set the xstop and xplay values to match the instance names of your stop button and play/pause buttons
//mute_btn.addEventListener(MouseEvent.CLICK, clickStop);
sound_btn.addEventListener(MouseEvent.CLICK, clickPlayPause);
soundChannel = sound.play();
isPlaying = true;
myVideo.stop();
function clickPlayPause(evt:MouseEvent) {
if (isPlaying) {
pausePoint = soundChannel.position;
soundChannel.stop();
isPlaying = false;
} else {
soundChannel = sound.play(pausePoint);
isPlaying = true;
}
}
button_01.addEventListener(MouseEvent.CLICK, onClick1);
button_02.addEventListener(MouseEvent.CLICK, onClick2);
button_03.addEventListener(MouseEvent.CLICK, onClick3);
button_04.addEventListener(MouseEvent.CLICK, onClick4);
button_05.addEventListener(MouseEvent.CLICK, onClick5);
button_06.addEventListener(MouseEvent.CLICK, onClick6);
function onClick1(e:MouseEvent):void
{
gotoAndStop(1);
}
function onClick2(event:MouseEvent):void
{
gotoAndStop(2);
}
function onClick3(event:MouseEvent):void
{
gotoAndStop(3);
}
function onClick4(event:MouseEvent):void
{
gotoAndStop(4);
}
function onClick5(event:MouseEvent):void
{
gotoAndStop(5);
}
function onClick6(event:MouseEvent):void
{
gotoAndStop(6);
}
The problem is your code for the sound is initialized on the frame that you send the timeline to when clicking button_01. It will reinitialize each time you do that. Try initializing your sound code one frame earlier so that you do not land on that frame ever again once your page loads.
You also might find that wrapping your pages into movieclips, and using visible = true/false to change sections might be a better approach than advancing the timeline to change sections. That method would not result in the sound code reinitializing each time you changed sections. something like this:
function onClick1(e:MouseEvent):void
{
hideAll();
section_01.visible = true;
}
function onClick2(event:MouseEvent):void
{
hideAll();
section_02.visible = true;
}
function onClick3(event:MouseEvent):void
{
hideAll();
section_03.visible = true;
}
function onClick4(event:MouseEvent):void
{
hideAll();
section_04.visible = true;
}
function onClick5(event:MouseEvent):void
{
hideAll();
section_05.visible = true;
}
function onClick6(event:MouseEvent):void
{
hideAll();
section_06.visible = true;
}
function hideAll():void
{
section_01.visible = false;
section_02.visible = false;
section_03.visible = false;
section_04.visible = false;
section_05.visible = false;
section_06.visible = false;
}
If you wanted tweened transitions you could use a tweening class to handle the transitions by tweening the current section out in the hide function and then tweening the next section in in its respective onCLick function.