Archive for the ‘AS3’ Category

MP3 Player in AS3

September 17, 2008

This the code which you may use it to create a MP3 player using AS3. Copy these scripts in a class called Mp3Player and use this class in your flash cs3 as follows.

var player:Mp3Player = new Mp3Player();
player.play('blah.mp3');
or
var player:Mp3Player = new Mp3Player();
player.playlist = ['item1.mp3','item2.mp3'];
player.next();

package {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	import flash.utils.clearInterval;
	import flash.utils.setInterval;		

	public class Mp3Player extends EventDispatcher {

		static public const EVENT_TIME_CHANGE:String = 'Mp3Player.TimeChange';
		static public const EVENT_VOLUME_CHANGE:String = 'Mp3Player.VolumeChange';
		static public const EVENT_PAN_CHANGE:String = 'Mp3Player.PanningChange';
		static public const EVENT_PAUSE:String = 'Mp3Player.Pause';
		static public const EVENT_UNPAUSE:String = 'Mp3Player.Unpause';
		static public const EVENT_PLAY:String = 'Mp3Player.Play';
		//
		public var playing:Boolean;
		public var playlist:Array;
		public var currentUrl:String;
		public var playlistIndex:int = -1;
		//
		protected var sound:Sound;
		protected var soundChannel:SoundChannel;
		protected var soundTrans:SoundTransform;
		protected var progressInt:Number;

		public function play( url:String ):void {
			clearInterval(progressInt);
			if ( sound ) {
				soundChannel.stop();
			}
			currentUrl = url;
			sound = new Sound();
			sound.addEventListener(Event.COMPLETE, onLoadSong);
			sound.addEventListener(Event.ID3, onId3Info);

			sound.load(new URLRequest(currentUrl));

			soundChannel = sound.play();
			if ( soundTrans ) {
				soundChannel.soundTransform = soundTrans;
			} else {
				soundTrans = soundChannel.soundTransform;
			}
			soundChannel.addEventListener(Event.COMPLETE, onSongEnd);
			playing = true;
			clearInterval(progressInt);
			progressInt = setInterval(updateProgress, 30);
			dispatchEvent(new Event(EVENT_PLAY));
		}
		public function pause():void {
			if ( soundChannel ) {
				soundChannel.stop();
				dispatchEvent(new Event(EVENT_PAUSE));
				playing = false;
			}
		}
		public function unpause():void {
			if ( playing ) return;
			if ( soundChannel.position < sound.length ) {
				soundChannel = sound.play(soundChannel.position);
				soundChannel.soundTransform = soundTrans;
			} else {
				soundChannel = sound.play();
			}
			dispatchEvent(new Event(EVENT_UNPAUSE));
			playing = true;
		}
		public function seek( percent:Number ):void {
			soundChannel.stop();
			soundChannel = sound.play(sound.length * percent);
		}
		public function prev():void {
			playlistIndex--;
			if ( playlistIndex < 0 ) playlistIndex = playlist.length - 1;
			play(playlist[playlistIndex]);
		}
		public function next():void {
			playlistIndex++;
			if ( playlistIndex == playlist.length ) playlistIndex = 0;
			play(playlist[playlistIndex]);
		}
		public function get volume():Number {
			if (!soundTrans) return 0;
			return soundTrans.volume;
		}
		public function set volume( n:Number ):void {
			if ( !soundTrans ) return;
			soundTrans.volume = n;
			soundChannel.soundTransform = soundTrans;
			dispatchEvent(new Event(EVENT_VOLUME_CHANGE));
		}
		public function get pan():Number {
			if (!soundTrans) return 0;
			return soundTrans.pan;
		}
		public function set pan( n:Number ):void {
			if ( !soundTrans ) return;
			soundTrans.pan = n;
			soundChannel.soundTransform = soundTrans;
			dispatchEvent(new Event(EVENT_PAN_CHANGE));
		}
		public function get length():Number {
			return sound.length;
		}
		public function get time():Number {
			return soundChannel.position;
		}
		public function get timePretty():String {
			var secs:Number = soundChannel.position / 1000;
			var mins:Number = Math.floor(secs / 60);
			secs = Math.floor(secs % 60);
			return mins + ":" + (secs < 10 ? "0" : "") + secs;
		}
		public function get timePercent():Number {
			if ( !sound.length ) return 0;
			return soundChannel.position / sound.length;
		}
		protected function onLoadSong( e:Event ):void {
		}
		protected function onSongEnd( e:Event ):void {
			if ( playlist )
				next();
		}
		protected function onId3Info( e:Event ):void {
			dispatchEvent(new Event(Event.ID3, e.target.id3));
		}
		protected function updateProgress():void {
			dispatchEvent(new Event(EVENT_TIME_CHANGE));
			if ( timePercent >= .99 ) {
				onSongEnd(new Event(Event.COMPLETE));
				clearInterval(progressInt);
			}
		}
	}
}

Current System Time using Timer()

September 11, 2008

This is about basically how to get your current system time using Timer() function using AS3.

 

For this you need to create four dynamic text boxes and name those as txtHrstxtMinstxtSecs, and txtDate.

 

Put the following actions in your movie frame and create a class and use these.

 

var time:Timer = new Timer(10);

tm.addEventListener(TimerEvent.TIMER, update);

function update(tevt:TimerEvent):void {

                         var now:Date = new Date();

                         var hr:Number = now.hours;

                         var min:Number = now.minutes;

                         var sec:Number = now.seconds;

                         if (hr > 12) {

                                                  hr -= 12;

                         }

                         txtHrs.text = String(hr);

                         if (min < 10) {

                                                  txtMins.text = “0″;

                         }

                         else {

                                                  txtMins.text = “”;

                         }

                         txtMins.appendText(String(min));

                         if (sec < 10) {

                                                  txtSecs.text = “0″;

                         }

                         else {

                                                  txtSecs.text = “”;

                         }

                         txtSecs.appendText(String(sec));

                         txtDate.text = now.toDateString();

}


time.start();

 

Now test your movie and you can see your system time on your movie display.

Try this!.

Car race game in AS3

August 19, 2008

Here is the car race game that I have just started in AS3.

/*
*    File        :    Main.as
*    Author        :    Karthik
*    Date        :    12 Aug 2008
*
*
*/

package {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import flash.display.Stage;

public class Main extends Sprite {

/*
*    Declerations
*/
var mcRoad            :MovieClip;
var mcCheckPoint    :MovieClip;
var mcLastCheckPoint:MovieClip;
var mcRoadLine        :MovieClip;
var mcLineContainer    :MovieClip;
var mcCar            :MovieClip;
var mcPlayButton    :MovieClip;
var mcSpeedoMeter    :MovieClip;
var mcGameOver        :MovieClip;
var i                :Number;
var trackLength        :Number        =    100;
var speedX             :Number        = 0;
var speedY             :Number        = 0;
var acceleration     :Number        = 0.75;
var friction         :Number        = 0.98;

/*
*    Function    :    Main
*    Param        :    NIL
*    Return        :    NIL
*    Description    :    Constructor method.
*/
public function Main() {
this.init();
}

/*
*    Function    :    EnterFrame
*    Param        :    NIL
*    Return        :    NIL
*    Description    :    Initialization method that adds all the required graphics,events to stage.
*/
public function init() {
//     Add the road graphics to the center of the stage.
mcRoad         =     new Road();
mcRoad.x     =     stage.stageWidth * 0.5;
mcRoad.y     =     stage.stageHeight * 0.5;
addChild(mcRoad);
//    Add the raod lines to the stage by duplicating it into multiple up to its track length
mcLineContainer        =    new MovieClip();
for(i=0;i<trackLength*0.5;i++) {
mcRoadLine        =    new Roadline();
mcRoadLine.x    =    stage.stageWidth * 0.5;
mcRoadLine.y    =    stage.stageHeight – i * 150;
mcLineContainer.addChild(mcRoadLine);
}
mcLastCheckPoint    = new Checkpoint();
mcLastCheckPoint.x    =    stage.stageWidth * 0.5;
mcLastCheckPoint.y    =    stage.stageHeight – i * 150;
mcLineContainer.addChild(mcLastCheckPoint);
addChild(mcLineContainer);
//    Add the checkpoint graphics to the center of the stage
mcCheckPoint    =    new Checkpoint();
mcCheckPoint.x    =    stage.stageWidth * 0.5;
mcCheckPoint.y    =    stage.stageHeight * 0.5;
addChild(mcCheckPoint);
//     Add the car graphic to the center of the stage.
mcCar         =     new Car();
mcCar.x     =     stage.stageWidth * 0.5;
mcCar.y     =     stage.stageHeight * 0.5;
addChild(mcCar);
//    Add the play button to the stage and make it to be clicked to start the game.
mcPlayButton                 =     new Playbutton();
mcPlayButton.buttonMode     =     true;
mcPlayButton.x                 =     stage.stageWidth * 0.80;
mcPlayButton.y                 =     stage.stageHeight * 0.5;
mcPlayButton.addEventListener(MouseEvent.CLICK, PlaybuttonClicked);
addChild(mcPlayButton);
}

/*
*    Function    :    EnterFrame
*    Param        :    Any Event
*    Return        :    NIL
*    Description    :    This EnterFrame function is equalent to onEnterFrame function.
*/
private function EnterFrame(event:Event):void {
/*if (Key.isDown(Keyboard.UP)) {
mcLineContainer.y     += 15;
mcCheckPoint.y        += 15;
}*/
if (Key.isDown(Keyboard.LEFT)) {
//speedX = speedX-acceleration;
mcCar.x -= 4;
if(mcCar.x <= stage.stageWidth * 0.39) {
mcCar.x += 4;
}
}
if (Key.isDown(Keyboard.RIGHT)) {
//speedX = speedX+acceleration;
mcCar.x += 4;
if(mcCar.x >= stage.stageWidth * 0.61) {
mcCar.x -= 4;
}
}
if (Key.isDown(Keyboard.UP)) {
speedY = speedY-acceleration;
}
if (Key.isDown(Keyboard.DOWN)) {
speedY = speedY+acceleration;
}
speedX                 = speedX*friction;
speedY                 = speedY*friction;
mcLineContainer.y     -= speedY;
mcCheckPoint.y         -= speedY;
mcSpeedoMeter.speedHand.rotation -= speedY/60;
if(mcCar.hitTestObject(mcLastCheckPoint)) {
stage.removeEventListener(Event.ENTER_FRAME, EnterFrame);
mcGameOver        =    new Gameover();
mcGameOver.x    =    stage.stageWidth * 0.5;
mcGameOver.y    =    stage.stageHeight * 0.5;
addChild(mcGameOver);
}
}

/*
*    Function    :    StartRace
*    Param        :    NIL
*    Return        :    NIL
*    Description    :    Start race function will activate keyboard event to stage and invokes the EnterFrame function
*                    to the stage Enter_Frame event.
*/
private function StartRace():void {
stage.addEventListener(Event.ENTER_FRAME, EnterFrame);
Key.initialize(stage);
}

/*
*    Function    :    PlaybuttonClicked
*    Param        :    Mouse Event
*    Return        :    NIL
*    Description    :    Function will invoke the start race function up on Play button clicked
*/
private function PlaybuttonClicked(event:MouseEvent):void {
StartRace();
mcPlayButton.play();
mcSpeedoMeter         =     new Speedometer();
mcSpeedoMeter.x     =     stage.stageWidth * 0.15;
mcSpeedoMeter.y     =     stage.stageHeight * 0.9;
mcSpeedoMeter.speedHand.rotation    =    0;
addChild(mcSpeedoMeter);
}
}
}

Get days between two given dates

August 8, 2008

public static function getDaysBetweenDates(date1:Date,date2:Date):int
{
var one_day:Number = 1000 * 60 * 60 * 24
var date1_ms:Number = date1.getTime();
var date2_ms:Number = date2.getTime();
var difference_ms:Number = Math.abs(date1_ms – date2_ms)
return Math.round(difference_ms/one_day);
}

Key.isDown in AS3

August 5, 2008

I have given the easy way to implement Key.isDown in AS3 here. This is the duplicated version from the original senocular’s post in KirupaForum (here)

Thanks to senocular

In ActionScript 2, you could use Key.isDown(keyCode) to determine whether or not a key was being pressed on the keyboard. This command is no longer available in ActionScript 3. In fact, there is no Key object in ActionScript 3. You can still access keyCodes by name, but through the Keyboard (flash.ui.Keyboard) class. For key recognition in ActionScript 3, you have to use keyboard events or, more specifically the KeyboardEvent.KEY_DOWN and KeyboardEvent.KEY_UP events. When a key is pressed on the keyboard, the KeyboardEvent.KEY_DOWN is dispatched and you can tell which key was pressed by checking KeyboardEvent.keyCode in the event handler. Same applies to keys being released in the KeyboardEvent.KEY_UP.

Using these events, you could recreate the functionality provided by the Key class in ActionScript 2. However, you should know that the KeyboardEvents only work when the Flash player has focus. This means a key could be pressed in Flash and released outside of Flash without Flash knowing that it was released (not having received the KEY_UP event). As a result, you should assume all keys released upon deactivation (loss of focus) of the Flash player. The following recreation of the Key class takes that into consideration.

// Key.as package {     import flash.display.Stage;     import flash.events.Event;     import flash.events.KeyboardEvent;     /**      * The Key class recreates functionality of      * Key.isDown of ActionScript 1 and 2. Before using      * Key.isDown, you first need to initialize the      * Key class with a reference to the stage using      * its Key.initialize() method. For key      * codes use the flash.ui.Keyboard class.      *      * Usage:      * Key.initialize(stage);      * if (Key.isDown(Keyboard.LEFT)) {      *    // Left key is being pressed      * }      */     public class Key {         private static var initialized:Boolean = false;  // marks whether or not the class has been initialized         private static var keysDown:Object = new Object()// stores key codes of all keys pressed         /**          * Initializes the key class creating assigning event          * handlers to capture necessary key events from the stage          */         public static function initialize(stage:Stage) {             if (!initialized) {                 // assign listeners for key presses and deactivation of the player                 stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);                 stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);                 stage.addEventListener(Event.DEACTIVATE, clearKeys);                 // mark initialization as true so redundant                 // calls do not reassign the event handlers                 initialized = true;             }         }         /**          * Returns true or false if the key represented by the          * keyCode passed is being pressed          */         public static function isDown(keyCode:uint):Boolean {             if (!initialized) {                 // throw an error if isDown is used                 // prior to Key class initialization                 throw new Error("Key class has yet been initialized.");             }             return Boolean(keyCode in keysDown);         }         /**          * Event handler for capturing keys being pressed          */         private static function keyPressed(event:KeyboardEvent):void {             // create a property in keysDown with the name of the keyCode             keysDown[event.keyCode] = true;         }         /**          * Event handler for capturing keys being released          */         private static function keyReleased(event:KeyboardEvent):void {             if (event.keyCode in keysDown) {                 // delete the property in keysDown if it exists                 delete keysDown[event.keyCode];             }         }         /**          * Event handler for Flash Player deactivation          */         private static function clearKeys(event:Event):void {             // clear all keys in keysDown since the player cannot             // detect keys being pressed or released when not focused             keysDown = new Object();         }     } }

ActionScript Function calls

August 1, 2008

var correctCallback:Function;
var incorrectCallback:Function;

enable.call();

function setCorrectCallbackFunction(funct:Function) {
correctCallback = funct;
}

function setIncorrectCallbackFunction(funct:Function) {
incorrectCallback = funct;
}

function enable():void {
[ code ....]

}
function checkClick(event:MouseEvent) {
if (event.target.name == “button”) {
correctCallback.call();
} else if (event.target.name == “buttonIncorrect”) {
incorrectCallback.call();
}
}