Sunday, 27 September 2009

the hit test using a circle and block

circle_mc.onPress = function() { this.startDrag(); }; circle_mc.onRelease = function() { this.stopDrag(); if (this.hitTest(block_mc)) { trace("you hit the block"); }} //have fun !

gravity with speed

onClipEvent (load) {
// gravity is what I called g in the tutorial. The
// higher g the harder the ball will fall.
// gravity = 0 can be set, as an experiment, but
// it will in fact create a "zero gravity" effect
// gravity < 0 will create an inverted gravity effect
gravity = 2 ;

// We set the speed of the ball when it is released.
speedx = 0 ;
speedy = 0 ;
}

onClipEvent (enterFrame) {

// We calculate the increase of speed
// speedx doesn't change
speedy = speedy + gravity ;

// We move the ball.
// speed/5 just makes the motion slower
this._x += speedx/5 ;
this._y += speedy/5 ;
}

//have fun

Saturday, 26 September 2009

action script for scaling an objects x width and y height, with rotation.

stop();
this.onEnterFrame=function(){
object_mc._rotation+=10;
object_mc._x-=5;
object_mc._x+=5;

press_btn.onPress=function() {
object_mc._height+=100;

}}
pressless_btn.onPress=function() {
object_mc._width-=100;
}

pressless_btn._x=10;

here is some action script for making a metronome

function startMet() {
if (_root.tempo_num>39 && _root.tempo_num<209) {
//set left dot alphas
ldot_mc._alpha = 100;
rdot_mc._alpha = 0;
playBeep();
speed_num = (60/_root.tempo_num);

tick_mc.rotateT1 = new Tween(this.tick_mc, "_rotation", none, startpos_num, (startpos_num+endpos_num*2), speed_num, true);
tick_mc.rotateT1.onMotionFinished = function() {
initiateDot();
this.yoyo();
};
}

//havefun!

move your objects with arrow keys using action script

var speed:Number = 4;
object_mc.onEnterFrame = function() {
if (Key.isDown(Key.RIGHT)) {
this._x = this._x+speed;
} else if (Key.isDown(Key.LEFT)) {
this._x = this._x-speed;
}
if (Key.isDown(Key.UP)) {
this._y = this._y-speed;
} else if (Key.isDown(Key.DOWN)) {
this._y = this._y+speed;
}
};

//have fun



Action Script explanation:

1.information_txt.text = "Use your arrow keys to move the balloon!";
1. Display instructions on the screen

2 .var speed:Number = 4;
2. Set the speed for the object

3. object_mc.onEnterFrame = function() {
3. Capture the onEnterFrame event of the object_mc movie clip

4. if (Key.isDown(Key.RIGHT)) {
this._x = this._x + speed;
} else if (Key.isDown(Key.LEFT)) {
this._x = this._x - speed;
}

4. Move horizontally if the RIGHT or LEFT arrow keys are pressed

5. if (Key.isDown(Key.UP)) {
this._y = this._y - speed;
} else if (Key.isDown(Key.DOWN)) {
this._y = this._y + speed;
}
};

5. Move vertically if the UP or DOWN arrow keys are pressed

We're done!

Test your Movie (Ctrl+Enter).

loading a movie clip using url

_root.MC.attachMovie(param).

//have fun

Friday, 25 September 2009

action script for making a sliding effect portfolio

//note when building this you will need, to build your images - buttons, inside (mc)
var cuurobj;
var easing = 6;
var hmiddle = Stage.width/2;
var vmiddle = Stage.height/2;
stop();
onEnterFrame = function () {
objh_v = _root.objholder_mc._y;
objh_h = _root.objholder_mc._x;
vdiff = vmiddle-objh_v;
hdiff = hmiddle-objh_h;
obj_h = _root.objholder_mc["object"+currobj+"_mc"]._x;
obj_v = _root.objholder_mc["object"+currobj+"_mc"]._y;
finalvdiff = vdiff-obj_v;
finalhdiff = hdiff-obj_h;
_root.objholder_mc._y += finalvdiff/easing;
_root.objholder_mc._x += finalhdiff/easing;
};
_root.objholder_mc.object1_mc.onPress = function () {
currobj = 2;

};
_root.objholder_mc.object2_mc.onPress = function () {
currobj = 3;
};
_root.objholder_mc.object3_mc.onPress = function () {
currobj = 4;
};
_root.objholder_mc.object4_mc.onPress = function () {
currobj = 1;
};
_root.objholder_mc.butt1_btn.onPress = function () {
currobj = 1;
}


//have fun!

action script code for making a thumbnail scroll bar in flash

_root.onEnterFrame = function() // this enables when we run the program
{

if(_root._xmouse<301) // the x axis using the mouse
{
myVar=false; // create your var
}

if(_root._ymouse>350) //if your mouse is higher then 350 pixels
{
myVar=true; // then your var is positive
}

if(_root._xmouse< 55 and myVar == false) //if your mouse is less the 55 //pixels
{
imgbar_mc.prevFrame(); //then your instance name will play the next
imgbar_mc.prevFrame(); // then your instance name will play the prev frame
}



if(_root._xmouse> 80 and myVar == true)
{
imgbar_mc.nextFrame();
imgbar_mc.nextFrame();
}

}
//have fun!

Wednesday, 23 September 2009

wheel rotation action script

this.onEnterFrame=function(){
wheel_mc._rotation+=5;
wheel_mc._x+=5;
}


var dir:Number=0;

right, 1 - move ro the left*/
wheel_mc._x=35;

this.onEnterFrame=function(){
if (dir==0){
wheel_mc._rotation+=5;
wheel_mc._x+=5;
if (wheel_mc._x==470){
dir=1;
}
}
if (dir==1){
wheel_mc._rotation-=5;
wheel_mc._x-=5;
if (wheel_mc._x==35){
dir=0;
}
}
}

// have fun!

get Volume action

mySound .getVolume ( )

// have fun!

trasform sound so that you can change the levels of sound into the speakers

mySound .setTransform( soundTransformObject )

leftOutput = left_input * ll + right_input * lr
rightOutput = right_input * rr + left_input * rl


ll = 100
lr = 0
rr = 100
rl = 0

// mono settings

ll = 100
lr = 100
rr = 0
rl = 0




//The following code creates a new soundTransformObject object and sets its properties so that sound from both channels will play only in the left channel. mySoundTransformObject = new Object;
mySoundTransformObject.ll = 100;
mySoundTransformObject.lr = 100;
mySoundTransformObject.rr = 0;
mySoundTransformObject.rl = 0;
//To apply the soundTransformObject object to a Sound object, you then need to pass the object to the Sound object using the setTransform method as follows:mySound.setTransform(mySoundTransformObject); The following example plays a stereo sound as mono; the soundTransformObjectMono has the following parameters. mySoundTransformObjectMono = new Object;
mySoundTransformObjectMono.ll = 50;
mySoundTransformObjectMono.lr = 50;
mySoundTransformObjectMono.rr = 50;
mySoundTransformObjectMono.rl = 50;
mySound.setTransform( soundTransformObjectMono );
//This example plays the left channel at half capacity and adds the rest of the left channel to the right channel; the soundTransformObjectHalf has the following parameters. mySoundTransformObjectHalf = new Object;
mySoundTransformObjectHalf.ll = 50;
mySoundTransformObjectHalf.lr = 0;
mySoundTransformObjectHalf.rr = 100;
mySoundTransformObjectHalf.rl = 50;
setTransform( soundTransformObjectHalf );
See alsoConstructor for the Object (object)

loads an mp3 sound

Sound.loadSound
Availability
Flash Player 6.

Usage


mySound.loadSound(" url ", isStreaming )


//have fun!

stop sound in flash

mySound .stop([" idName "])


//have fun!

start a sound in action script

mySound .start([ secondOffset , loop ])


//have fun!

get url action script

//action script for loading a url webpage;

myButton_btn.onRelease=function(){
getURL("http://www.tutorial5.com/", "_blank");
}




//hav fun!

19th century influence to modern art.


Piet, Mondrian.



This image is of Mondrian's work.

























My full discription for these two images is show below.





Piet Mondrian was a Painter in the late 19Th century, his work has influenced millions of people since his death in 1944, I chose Piet Mondrian because of his style of work, I like the use of his Strong bold lines, that show depth and or shadow, and the use of his colour is so different to a painter like Van Goph.





A composition with red, yellow and blue, composed by Piet Mondrian from possesses a sense of simplicity whilst simultaneously comprises of complexity. Mondrian has used oil on canvas as his materials and has created the artwork Composition with red, yellow and blue is currently located at the Tate Gallery. Piet Mondrian was Dutch but spent most of his time in Holland and Paris. The art movement that Composition with red, yellow and blue was created in was Surrealism. Piet Mondrian was associated with the mystique that an artwork could attain. He joined the Theosophical Society
in 1909, and hence forward began to produce works, which had an abstract sense and another meaning to them. When Mondrian went to Paris - his inspiration - the Cubists, Mondrian viewed the work there in 1911-1913. After returning to Holland





After Looking into Mondrian I have been looking




at modern art work that has been influenced by him,



The image on the left <<>

If we look closely at the screen shot, we can see where they have got there ideas from, there use of layers overlapping each other are like Mondrian's colour overlaps in the top image.


The website is made using blocks just like the image above. and they have used Strong bold lines to show construction work. they have placed there navigation bars in certain blocks, and used a contrasting colour scheme method for there interface in the same way Mondrian has.













This is the original poster by Toulouse Lautrec .























This is the modern day poster I found that it is influenced by Toulouse Lautrec's style of poster design.

Toulouse Lautrec, like no other nineteenth century artist was deeply influenced by Japanese woodblock prints. Just like the exuberant life of the amusement quarters of the Japanese Edo period, it was the nightlife of Montmartre in Paris, which inspired the works of this incredible artist. And like the great Ukiyo-e artist Utamaro, Toulouse Lautrec not only painted the world of brothels, but was a frequent guest himself.


in the top image of Lautrecs, you can see, he use,s a style of graphic design but very basic as in the 19th century, people did'nt have the design knowledge and equipment as we do today.


However Lautrec has developed a poster which does tell an audience whats happening in the poster. In his poster it appears that there is a Concert Ball at the Moulin Rouge. To show this information he has used red text onto a white canvas, also he has painted additional text black to show the important information standing out.


To finish this poster he has drawn a illustration of what the style of the night should intend to look like.

In the picture there are people dancing and two main characters in the for ground.

This will give viewers a visual point of perspective to whats happening.

A century has past now and people still use Lautrecs method when designing a Poster.

1 Clear text and information.

2 Good use of font.

3 good choice of colours to your theme.

4 and a clear visual illustration or image, to give a visual appearance on the subject.


If you look at the film poster I found on the Internet, it shows all the meanings in the same way Lautrec did in his poster. The only reason why this poster looks better then Lautrecs piece is because it was made using the design process, and made with better technology that didn't exist in the 19th century.


But the film poster I found uses a image for visual appearance, it uses a strong Head line in the right colour and font related to its theme,, and also it reflects back to Lautrec's work.






















Starey Night by Van Goph.






Van gogh's use of style stippling, hatching, swirls, and a un real like painting effect.
































This painting was painted by Stefan Duncan.
a artist inspired by Van Goph of the 19th century.
You can see in the top image that his stlye of painting is almost identical and almost the same to Van Goph's.
His use of brush strokes are in the form of swirls like Vincents van Goph's, and the colours bold and strong also. The painting looks almost fairy tale ish, just like the above painting.




  • Sources of research.


    http://www.eyeconart.net/history/19th_century.htm

    http://www.ethnicpaintings.com/painting-trivia/19th-centuary-painting.html Century

    http://en.wikipedia.org/wiki/Western_art_history :Western art history

    http://stefanduncangallery.com/Old%20Pages/glory%20tree.JPGinfluenced by van gogh.



    http://imagecache2.allposters.com/images/pic/EUR/2300-2037~Moulin-Rouge-Posters.jpg

    http://www.webdesign.org/img_articles/14466/_121.jpg


    http://garcya.us/images/shout.jpg

    http://www.britannica.com/EBchecked/topic/389102/Piet-Mondrian/4943/Influence-of-Post-Impressionists-and-Luminists : mondrian life

    http://cealdecote.files.wordpress.com/2007/12/mondrian.jpg


    http://images.google.co.uk/imgres?imgurl=http://ursamajorwebworks.com/images/2007/0704/mondrian.jpg&imgrefurl=http://ursamajorwebworks.com/images/2007/0704/mondrian.html&usg=__5nxFpGzeJeZgqv0UAddjTdTydwA=&h=768&w=1024&sz=57&hl=en&start=8&um=1&tbnid=CsN-vqEJwK0U2M:&tbnh=113&tbnw=150&prev=/images%3Fq%3Dmondrian%2Bposters%26hl%3Den%26um%3D1 :mondrian interface


    http://img407.imageshack.us/img407/1555/toothbrushaf8.jpg


    http://farm2.static.flickr.com/1024/1430634948_543c893e28.jpg





















































Tuesday, 22 September 2009

bouncing ball

function BlueBall() {
startFallingBall();

setupResetFunctionality();
}

function startFallingBall() {
timer=0;
initialPos=this.y;
this.addEventListener(Event.ENTER_FRAME, moveBallDown);
}
// Responsible for moving the ball down
function moveBallDown(e:Event) {
timer+=1;
this.y = initialPos + .5*gravity*(timer * timer);
checkBottomBoundary();
}
this.y = initialPos + .5*gravity*(timer * timer);
function checkBottomBoundary() {
if (this.y+this.height>stage.stageHeight) {
finalPos=this.y;

stopFallingBall();
}
}
This method checks to see if
function stopFallingBall() {
this.removeEventListener(Event.ENTER_FRAME, moveBallDown);
// If the bounce is a 10% of the ball's height, just stop
// the bounce
if (finalPos-initialPos<.1*this.height) {
stopRisingBall();
} else {
startRisingBall();
}
}

if (finalPos-initialPos<.1*this.height) {
stopRisingBall();
} else {
startRisingBall();
}

// Sets up what is needed to start bouncing the ball up
function startRisingBall() {
initialSpeed=decay*Math.sqrt(2*Math.abs(finalPos-initialPos));
timer=0;
currentPos=this.y;
this.addEventListener(Event.ENTER_FRAME, moveBallUp);
}

initialSpeed=decay*Math.sqrt(2*Math.abs(finalPos-initialPos));

// Responsible for moving the ball up
function moveBallUp(e:Event) {
timer+=1;

//Storing the position of the ball before and after it moves
var positionA:Number=this.y;
this.y = currentPos - initialSpeed*timer + .5*gravity*(timer * timer);
var positionB=this.y;

checkTopBoundary(positionA, positionB);
}
this.y = currentPos - initialSpeed*timer + .5*gravity*(timer * timer);

// Checks when the ball has hit the top of the bounce
function checkTopBoundary(firstPos:Number, secondPos:Number) {
if (secondPos>firstPos) {
stopRisingBall();
startFallingBall();
}
}

var timer:Number=0;
var initialPos:Number=0;
var finalPos:Number=0;
var currentPos:Number=0;
var initialSpeed:Number=0;
var startPosition:Number=0;
var gravity:Number = 1;

//Adjust this to increase or decrease the
//number of bounces
var decay:Number = .9;
}

follow the mouse with ease.

// action script 2


onClipEvent (load) {
_x = 0;
_y = 0;
speed = 5;
}
//we can change the speed of the mouse here from 5 to 10
onClipEvent (enterFrame) {
endX = _root._xmouse;
endY = _root._ymouse;
_x += (endX-_x)/speed;
_y += (endY-_y)/speed;
}

//have fun

drag and drop function in action script

here is a quick drag and drop function ive written.
note the redcirlce is the object or movie clip

redCircle.onPress = function(){
startDrag(this,true)
}

redCircle.onRelease = function(){
this.stopDrag();
}

hav fun !

gravity in action script

hre i have written a simple code to show how gravity can me applied to any object in flash.

// create your variables for use later
var gravity:Number = 2;
var velocity:Number = 0;


These are two defined variables - gravity and velocity. Gravity is a constant downward acceleration, set to 2. Velocity is the current vertical speed of the object in question.


enter the following


if ( this._y >= 453 and _root.velocity < 2.5 and _root.velocity >= 0 ) { this._y = 460; _root.velocity =0; }
else {
if ( this._y >= 460 and _root.velocity>0 ) { _root.velocity = -_root.velocity * .7 ; }
this._y += _root.velocity;
_root.velocity += _root.gravity;
}

scroll bar

Create 2 lyers "actions" and "Lyer 1"

Add actionscript for lyer "actions" on frame 1 :


ms = textbox.Message.maxscroll; if (ms>1) { if (dragpress<1) { scale = 138/ms; _root.textbox.scrollbar.scrollbox._yscale = 200/textbox.Message.maxscroll; _root.textbox.scrollbar.scrollbox._y = -68+((textbox.Message.scroll-1)*scale); if (textbox.scrollbar._visible == false) { _root.textbox.scrollbar._visible = true; } } else if (textbox.scrollbar.scrollbox._y<-66 and move<0) { move = 0; textbox.scrollbar.scrollbox._y = -68; } else if (textbox.scrollbar.scrollbox._y+textbox.scrollbar.scrollbox._height>69 and move>0) { move = 0; } else { textbox.scrollbar.scrollbox._y = textbox.scrollbar.scrollbox._y+(move*scale); textbox.Message.scroll = ((textbox.scrollbar.scrollbox._y+68)/scale)+1.2; } } else { if (textbox.scrollbar._visible == true) { textbox.scrollbar._visible = false; } }
Add actionscript for lyer "actions" on frame 2:

gotoAndPlay (1);
Create MC (emailmovie) for lyer "Lyer 1" and in INSTANS window name is a "textbox"



Edit MC (emailmovie)



Lyer 2 has an actionscript on frame 1

loadVariables ("message.txt", "_root.textbox"); stop ();
Lyer 1 has a text field on frame 1
Lyer 3 has a MC scrollbar on frame 1 and in INSTANS window name is a "scrollbox"

the gotoAndPlay statment

Goto statement: To move from one scene to another or from one frame to another frame, Goto statement is used.


Example:
On (press)
{
Goto and play (5);
}

(Or) on (press)
{
Goto and stop (1);
}

We cannot have Goto statement alone in the script. It is always clubbed with Play or Stop statement.

PLAY & STOP

Using these actions, the movie can be played or stopped.

The play and stop are vital commands of action script. If we uncheck the play button, it automatically becomes stop. Goto, play and stop statements are always combined.

Play and stop statements can be added separately, but goto statement cannot be separated.


Example:

Like this, we can have script

On (press)
{
Play ( );
}
On (release)
{
Stop ( );
}



And not like this:

On (press)
{
Goto;
}

have fun!

loading external images with a button

import gs.*;
import gs.easing.*;

//Create an array which will contain all image URLs
var imageURLs = new Array();

//This array will contain all the image holders
var imageHolders = new Array();

//We want to know how many images have been loaded
var loadedImages:Number = 0;

//Add all of our image URLs into the array
imageURLs.push("http://flashmymind.com/images/image1.gif");
imageURLs.push("http://flashmymind.com/images/image2.gif");
imageURLs.push("http://flashmymind.com/images/image3.gif");
imageURLs.push("http://flashmymind.com/images/image4.gif");
imageURLs.push("http://flashmymind.com/images/image5.gif");
imageURLs.push("http://flashmymind.com/images/image6.gif");
imageURLs.push("http://flashmymind.com/images/image7.gif");
imageURLs.push("http://flashmymind.com/images/image8.gif");
imageURLs.push("http://flashmymind.com/images/image9.gif");
imageURLs.push("http://flashmymind.com/images/image10.gif");
imageURLs.push("http://flashmymind.com/images/image11.gif");
imageURLs.push("http://flashmymind.com/images/image12.gif");
imageURLs.push("http://flashmymind.com/images/image13.gif");
imageURLs.push("http://flashmymind.com/images/image14.gif");
imageURLs.push("http://flashmymind.com/images/image15.gif");
imageURLs.push("http://flashmymind.com/images/image16.gif");
imageURLs.push("http://flashmymind.com/images/image17.gif");
imageURLs.push("http://flashmymind.com/images/image18.gif");
imageURLs.push("http://flashmymind.com/images/image19.gif");
imageURLs.push("http://flashmymind.com/images/image20.gif");

//The number of rows and columns we will have
var rows:Number = 4;
var columns:Number = 5;

//Store the image width and height (40x40)
var imageWidth:Number = 40;
var imageHeight:Number = 40;

//Padding between the images
var padding:Number = 1.3;

//Left edge space
var left:Number = 20;

//Create the image holders (= empty movie clips) and position them on the stage
for (var i = 0; i < rows; i++) {

for (var j = 0; j < columns; j++) {

//Create a new holder
var imageHolder:MovieClip = new MovieClip();

//Position the holder
imageHolder.x = left + j * imageWidth * padding;
imageHolder.y = i * imageHeight * padding;

//Add a StarPreloader to the center of the holder
var preloader:StarPreloader = new StarPreloader();
preloader.x = imageWidth / 2;
preloader.y = imageHeight / 2;
imageHolder.addChild(preloader);

//We need to know which preloader belongs to which image holder,
//so we set the preloader to be a property of the holder.
imageHolder.preloader = preloader;

//Add ENTER_FRAME so we can rotate the preloader
preloader.addEventListener(Event.ENTER_FRAME, rotatePreloader);

//Add the holder to the stage
addChild(imageHolder);

//Add the holder to the imageHolders array
imageHolders.push(imageHolder);
}
}

//Call the function that loads an image that is first in the imageURLs array
loadImage();

//This function loads the first image in the imageURLs array
function loadImage():void {

//Create the loader
var loader:Loader = new Loader();

//Get the URL to load
var urlRequest:URLRequest = new URLRequest(imageURLs[0]);

//Load the image
loader.load(urlRequest);

//Listen when the loading is complete
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);

//Remove the first URL in the imageURLs array since we
//started to load that image.
imageURLs.splice(0,1);
}

//This function is called when an image is loaded
function imageLoaded(e:Event):void {

//Save the loaded bitmap to a local variable
var image:Bitmap = (Bitmap)(e.target.content);

//Save the image's holder to a local variable
var holder:MovieClip = imageHolders[loadedImages];

//Add the image to the holder
holder.addChild(image);

//Tween the image holder
TweenLite.from(holder, 3, {alpha: 0});

//Tween the preloader.
//We call the function "tweenFinished" when the animation is done.
//We pass the preloader and the image holder as parameters to the function.
TweenLite.to(holder.preloader, 1, {scaleX: 2, scaleY: 2, alpha: 0,
onComplete:tweenFinished, onCompleteParams:[holder.preloader, holder]});

//Update the loaded images count
loadedImages++;

//We load the next image if there are still more URLs in the array
if (imageURLs.length > 0) {
loadImage();
}
}

//This function rotates a preloader
function rotatePreloader(e:Event):void {

//Rotate the preloader
e.target.rotation += 5;
}

//This function is called when a preloader is finished tweening
function tweenFinished(preloader:MovieClip, holder:MovieClip):void {

//Remove the preloader from the holder
holder.removeChild(preloader);
}

action script for creating a mp3 player (action script 3)

How To Code A Full Functional MP3 Player Using ActionScript 3.0







create a new flash file (action script 3) type the following code.

var track:Sound = new Sound;

var index:Number = 0;

var trackPos:Number = 0;

var trackOn:Boolean = false;

var trackXML:XML;

var trackList:XMLList;

var urlRequest:URLRequest;

var urlLoader:URLLoader;

var newTrack:Sound;

var newUrlRequest:URLRequest;

var chan:SoundChannel = new SoundChannel();

/* Rewind or FastForward rate */

const SEARCH_RATE:int = 1500;

/* XML file used to load the tracks */

const XML_FILE:String = "tracks.xml";First we create a new Sound object called track and then we initiate some variables that we will require to keep trail of the mp3 file that is being played. Then we define more variables that we will use in our code; these variables include the SoundChannel object.

For our mp3 player, we will be using an XML file to load our tracks. So create a simple xml file named tracks.xml and save it in the same place where your swf and fla files are located. This will be used to store the mp3 information such as track title, track performer, album…etc. mine looks like this. It is ok if yours is different as long as you know how to call the information appropriatley then you are fine, but I recommend you use the same structure to make sure everything works as described:





Performer 1
your_1.mp3



Performer 2
your_2.mp3



Performer 3
your_3.mp3

now we need to be able to access the xml file but first we will load it and then check whether the loading action is complete so type the following after you variables declarations:

// create a new URLRequest object and use to reference the XML file

urlRequest = new URLRequest(XML_FILE);

// create a new URLLoader object to load the XML file

urlLoader = new URLLoader(urlRequest);

urlLoader.addEventListener(Event.COMPLETE, onceLoaded);

urlLoader.load(urlRequest);Don’t test the movie yet if you do you will get an error because we didn’t create onceLoaded function yet, that’s our checking function. The function is added now

function onceLoaded(e:Event):void {

trackXML = new XML(e.target.data);

trackList = trackXML.track;

urlRequest = new URLRequest(trackList[index].path);

track.load(urlRequest);

}This function checks to see if the xml file has completely loaded and then loads the information to our mp3 player.

Adding Functionality to Play Button

Using the instances of buttons created in the previous tutorial we add this to make the buttons respond to our clicking events, the first one is play button:

play_mc.addEventListener(MouseEvent.CLICK, playTrack);Then add the playTrack function that will enable you to play the mp3 when the event of clicking play button as follows:

function playTrack(e:MouseEvent):void {

if (!trackOn) {

newUrlRequest = new URLRequest(trackXML.track[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play(trackPos);

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

}

}Now you if you test the movie you will be able to hear your first track play when you click the play button. I’m excited already, you?

Adding Functionality to Stop Button

But what if we wanted to the sound to stop? This is where the stop button becomes handy and we do that by adding the following line of code after:

stop_mc.addEventListener(MouseEvent.CLICK, stopTrack);

ffunction stopTrack(e:MouseEvent):void {

if (trackOn) {

chan.stop();

trackPos = 0;

play_mc.addEventListener(MouseEvent.CLICK, playTrack);

trackOn = false;

play_mc.visible = true;

}

}If you test the movie you should be able to play and then stop the sound as you wish. That wasn’t so bad wasn’t it!

Adding Functionality to Next Button

Now we want to enable our mp3 player to jump to another track, because the track we are listening to might be too boring or we are sick of it, after repeatedly listening to it while testing the movie. We do that by adding this code that targets the next button:

next_btn.addEventListener(MouseEvent.CLICK, nextTrack);

function nextTrack(e:MouseEvent):void {

if (index < trackList.length() - 1) {

index++;

}else{

index = 0;

}

chan.stop();

newUrlRequest = new URLRequest(trackList[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play();

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

track = newTrack;

}Adding Functionality to Previous Button

Maybe we changed our minds and we want to go back to the same track so what do we do? we add the next lines of code to enable the previous button:

prev_mc.addEventListener(MouseEvent.CLICK, prevTrack);

function prevTrack(e:MouseEvent):void {

if (index > 0) {

index--;

}else{

index = trackList.length() - 1;

}

chan.stop();

newUrlRequest = new URLRequest(trackList[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play();

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

track = newTrack;

}Adding Functionality to Pause Button

We also want to be able to pause tracks whenever we want. That’s achieved by adding the following code to our action panel;

pause_mc.addEventListener(MouseEvent.CLICK, pauseTrack);

function pauseTrack(e:MouseEvent):void {

if (trackOn) {

trackPos = chan.position;

chan.stop();

play_mc.visible = true;

play_mc.addEventListener(MouseEvent.CLICK, playTrack);

trackOn = false;

}

}Adding Functionality to Fast-forward and Rewind Buttons

As it is, your player is already fully functional but we also want to add a fast-forward and rewind functionality to our player. We can add these features by adding the following lines of code in the actionscript panel. First the fast-forward functionality:

ffwrd_mc.addEventListener(MouseEvent.CLICK, ffwrdTrack);

function ffwrdTrack(e:MouseEvent):void {

if (trackOn){

trackPos = chan.position;

chan.stop();

chan = track.play(trackPos + SEARCH_RATE);

chan.addEventListener(Event.SOUND_COMPLETE, playNext);

}

}and the code for enabling rewind functionality is as follows:

rewind_mc.addEventListener(MouseEvent.CLICK, rwndTrack);

function rwndTrack(e:MouseEvent):void {

if (trackOn) {

trackPos = chan.position;

chan.stop();

chan = track.play(trackPos - SEARCH_RATE);

}

}It is important to add play next function to our fastforward button so that when the track reach the end next track starts, so make changes to ffwrdTrack function as shown by adding chan.addEventListener(Event.SOUND_COMPLETE, playNext); and add the following playNext function as well:

function ffwrdTrack(e:MouseEvent):void {

if (trackOn){

trackPos = chan.position;

chan.stop();

chan = track.play(trackPos + SEARCH_RATE);

chan.addEventListener(Event.SOUND_COMPLETE, playNext);

}

}

function playNext(e:Event):void {

if (index < trackList.length() - 1) {

index++;

}else{

index = 0;

}

chan.stop();

newUrlRequest = new URLRequest(trackList[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play(0);

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

track = newTrack;

chan.addEventListener(Event.SOUND_COMPLETE, playNext);

}Displaying Track Information

In order to display track info we need to create some text areas so create two new layers named performer info and title info, respectively and grab the text tool and create two dynamic text areas with Arial type and 11 px. Call the first one performer_txt and second title_txt. This is crucial in order for the code to work properly. Keep each text area in its own layer.

We also need to add some coding to our function in order to display the text when the mp3 player starts playing or next and previous track is selected. Add the following code

title_txt.text = trackList[index].title;

performer_txt.text = trackList[index].performer;where necessary in playTrack, nextTrack, prevTrack, and playNext functions. The complete code after re-arranging and adding is shown below:

var track:Sound = new Sound;

var index:Number = 0;

var trackPos:Number = 0;

var trackOn:Boolean = false;

var trackXML:XML;

var trackList:XMLList;

var urlRequest:URLRequest;

var urlLoader:URLLoader;

var newTrack:Sound;

var newUrlRequest:URLRequest;

var chan:SoundChannel = new SoundChannel();

//--- Rewind or FastForward rate ---\\

const SEARCH_RATE:int = 1500;

//--- XML file used to load the tracks ---\\

const XML_FILE:String = "tracks.xml";

urlRequest = new URLRequest(XML_FILE);

urlLoader = new URLLoader(urlRequest);

urlLoader.addEventListener(Event.COMPLETE, onceLoaded);

urlLoader.load(urlRequest);

function onceLoaded(e:Event):void {

trackXML = new XML(e.target.data);

trackList = trackXML.track;

urlRequest = new URLRequest(trackList[index].path);

track.load(urlRequest);

}

play_mc.addEventListener(MouseEvent.CLICK, playTrack);

stop_mc.addEventListener(MouseEvent.CLICK, stopTrack);

next_mc.addEventListener(MouseEvent.CLICK, nextTrack);

prev_mc.addEventListener(MouseEvent.CLICK, prevTrack);

pause_mc.addEventListener(MouseEvent.CLICK, pauseTrack);

ffwrd_mc.addEventListener(MouseEvent.CLICK, ffwrdTrack);

rewind_mc.addEventListener(MouseEvent.CLICK, rwndTrack);

function playTrack(e:MouseEvent):void {

if (!trackOn) {

newUrlRequest = new URLRequest(trackXML.track[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play(trackPos);

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

title_txt.text = trackList[index].title;

performer_txt.text = trackList[index].performer;

}

}

function stopTrack(e:MouseEvent):void {

if (trackOn) {

chan.stop();

trackPos = 0;

play_mc.addEventListener(MouseEvent.CLICK, playTrack);

trackOn = false;

play_mc.visible = true;

}

}

function nextTrack(e:MouseEvent):void {

if (index < trackList.length() - 1) {

index++;

}else{

index = 0;

}

chan.stop();

newUrlRequest = new URLRequest(trackList[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play();

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

track = newTrack;

title_txt.text = trackList[index].title;

performer_txt.text = trackList[index].performer;

}

function prevTrack(e:MouseEvent):void {

if (index > 0) {

index--;

}else{

index = trackList.length() - 1;

}

chan.stop();

newUrlRequest = new URLRequest(trackList[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play();

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

track = newTrack;

title_txt.text = trackList[index].title;

performer_txt.text = trackList[index].performer;

}

function pauseTrack(e:MouseEvent):void {

if (trackOn) {

trackPos = chan.position;

chan.stop();

play_mc.visible = true;

play_mc.addEventListener(MouseEvent.CLICK, playTrack);

trackOn = false;

}

}

function ffwrdTrack(e:MouseEvent):void {

if (trackOn){

trackPos = chan.position;

chan.stop();

chan = track.play(trackPos + SEARCH_RATE);

chan.addEventListener(Event.SOUND_COMPLETE, playNext);

}

}

function rwndTrack(e:MouseEvent):void {

if (trackOn) {

trackPos = chan.position;

chan.stop();

chan = track.play(trackPos - SEARCH_RATE);

}

}

function playNext(e:Event):void {

if (index < trackList.length() - 1) {

index++;

}else{

index = 0;

}

chan.stop();

newUrlRequest = new URLRequest(trackList[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play(0);

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

track = newTrack;

chan.addEventListener(Event.SOUND_COMPLETE, playNext);

title_txt.text = trackList[index].title;

performer_txt.text = trackList[index].performer;

}Adding Spectrum

Our last task is to create a spectrum ……

Create a new layer and call it spectrum then press F8 to create a new empty movie clip call it spectrum. In the editing mode of this newly created movie clip name the first layer rectangle and the second actions. Draw a rectangle 40px wide and 18px high that we’ll use as a guide, so right click the rectangle layer and select Guide. Now add the following code. This is taken from the help file modified a little bit to suite our mp3 player:

addEventListener(Event.ENTER_FRAME, onEnterFrame);

function onEnterFrame(event:Event):void {

var bytes:ByteArray = new ByteArray();

const PLOT_HEIGHT:int = 9;

const CHANNEL_LENGTH:int = 20; //256;

SoundMixer.computeSpectrum(bytes, false, 0);

var g:Graphics = this.graphics;

g.clear();

g.lineStyle(0, 0xFF9933);

g.beginFill(0xFF9933);

g.moveTo(0, PLOT_HEIGHT);

var n:Number = 0;

for (var i:int = 0; i < CHANNEL_LENGTH; i++) {

n = (bytes.readFloat() * PLOT_HEIGHT);

g.lineTo(i * 2, PLOT_HEIGHT - n);

}

g.lineTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);

g.endFill();

g.lineStyle(0, 0xFF9933);

g.beginFill(0xFF9933, 0.5);

g.moveTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);

for (i = CHANNEL_LENGTH; i > 0; i--) {

n = (bytes.readFloat() * PLOT_HEIGHT);

g.lineTo(i * 2, PLOT_HEIGHT - n);

}

g.lineTo(0, PLOT_HEIGHT);

g.endFill();

}Back in the main time line just position the empty movie clip where it should and your player should work perfectly. Let me know if you have problems. Later I will upload the files for downloads.

That concludes our tutorial I hope it was clear and helpful to all who want to create fully functional mp3 players. Of course there are more features that can be added to make this player even better, such as track list, elapsed time, mute button, skin color button…etc. but for now this should be sufficient enough. I hope you enjoyed and please leave your comments.

Thank you for reading.



Tags: action script, flash, mp3-player

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
« How to Create an MP3 Player from Design to Finish40 Exceptionally Beautiful Wordpress Themes »Related Posts 26 Responses to “How To Code A Full Functional MP3 Player Using ActionScript 3.0” MAD says:
August 31, 2009 at 8:20 amI should try both tutorials when I am free. But looks great.

Reply j000 says:
August 31, 2009 at 12:55 pmThanks Later I want to experiment with colors and also add more functionality to the mp3 player what do you think?

Reply John says:
August 31, 2009 at 5:43 pmPlease do! Maybe include a settings file to specify colours…

Reply j000 says:
August 31, 2009 at 6:19 pmMaybe in future tutorials this one is a simple mp3 player that is not built using classes.

Reply haungo.net says:
September 1, 2009 at 3:17 amThanks! nice little player there. I’m looking forward to the source.

-B

Reply j000 says:
September 1, 2009 at 8:20 amYeah I will upload it once I figure out how :\ the files are too large maybe without the mp3s!!

Reply j000 says:
September 1, 2009 at 9:03 amSource code and files are available now

Reply 45+ Awesome Links for Web Designers - partytow for all says:
September 2, 2009 at 1:34 am[...] How To Code A Full Functional MP3 Player Using ActionScript 3.0 [...]

Reply Candy says:
September 3, 2009 at 8:36 amHi,
I’ve followed nearly every step of this tutorial, as well as the previous one, and my player looks great, but it doesn’t work.

I created an “actions” layer, and cut and pasted all of your code into this layer. I’m not sure if this is what was intended. Any help would be appreciated!

Reply
j000 says:
September 3, 2009 at 9:13 amActually you right, if you cut and pasted the code into an action layer frame one, then the player should work fine. As long as, you named the instances on the stage with the same names in the actionscript code. Why don’t you download the source files and check if this will help here http://flashjourney.com/wp-content/uploads/2009/08/Creating-Simple-MP3-Player.rar

Let me know if it works and I would love to see how everyone created their mp3 player if a bit different from this.

Reply MP3 Player em Flash com ActionScript 3.0 « Flash Professional says:
September 3, 2009 at 11:58 am[...] Para conhecer o tutorial visite o link: http://flashjourney.com/2009/08/30/how-to-code-a-full-functional-mp3-player-using-actionscript-3-0/ [...]

Reply jufaily says:
September 4, 2009 at 5:20 pmMaybe I will try this with green or blue color for buttons and screen. Cool nonetheless.

Reply Steve says:
September 7, 2009 at 8:58 amHow would you add an autostart feature to this? It’s a great player!

Reply ladas says:
September 9, 2009 at 1:14 amHi! already did the mp3 player it worked fine, but i tried to put it on my web page with everything on it and it doesn’t play.

help please!

Reply MAD says:
September 9, 2009 at 8:06 amHi Ladas, it would help if you can provide more information on your issue. But it might be that the player can not find either the xml file or the mp3 files.

Reply
ladas says:
September 9, 2009 at 3:07 pmthat’s what i thought, because i had uploaded all the files to the same folder. can you tell me why?

Reply
MAD says:
September 11, 2009 at 10:22 amLadas,
you may need to change the following statement to include the full URL where your xml file resides

//— XML file used to load the tracks —\\
const XML_FILE:String = “tracks.xml”;

so instead of only “tracks.xml” you may write “http://yoursite.com/folder/folder/tracks.xml”
You also need to update your XML file to include the full path where the mp3 files are located. This should work, see the demo at the beginning of the article.

Reply Lukaz says:
September 9, 2009 at 10:37 pmHi! I just want to know if it´s possible to start automatically the first mp3 when I execute the swf.
thanks!!

Lukaz

Reply MAD says:
September 11, 2009 at 10:20 amHi Lukaz,
You can update your onceLoaded function as follows; this should do the trick.

function onceLoaded(e:Event):void {
trackXML = new XML(e.target.data);
trackList = trackXML.track;
urlRequest = new URLRequest(trackList[index].path);
track.load(urlRequest);

if (!trackOn) {
newUrlRequest = new URLRequest(trackXML.track[index].path);
newTrack = new Sound(newUrlRequest);
chan = newTrack.play(trackPos);
play_mc.removeEventListener(MouseEvent.CLICK, playTrack);
trackOn = true;
title_txt.text = trackList[index].title;
performer_txt.text = trackList[index].performer;
}
}

Regards,

Reply j000 says:
September 11, 2009 at 7:16 pmNow mp3 demo is active and there are new buttons for downloading and view the demo

Reply MAD says:
September 12, 2009 at 9:39 amA question from Owen Evans:
“Hi there, first just want to say thanks for posting your excellent tutorial on how to create a flash mp3 player. I have one problem thought that I hope you can help me with. After following your tutorial and making a MP3 to my site, I found my site takes longer to load. Is this because it is loading all the mp3 files? Or are they supposed to stream?”

Reply MAD says:
September 12, 2009 at 9:41 amEvans, my guess would be because it is loading all the large mp3 files. You can use The SoundMixer.bufferTime property to stream the file; see an example below:

import flash.media.Sound;
import flash.media.SoundLoaderContext;
import flash.net.URLRequest;

var s:Sound = new Sound();
var req:URLRequest = new URLRequest("bigSound.mp3");
var context:SoundLoaderContext = new SoundLoaderContext(8000, true);
s.load
s.true

Wednesday, 16 September 2009

summerise design

After watching the following program,

http://www.bbc.co.uk/iplayer/episode/b00mw165/Design_for_Life_Episode_1/

I knew and understood why the two students were sent home from Paris.

This was because he wanted more from them, he wanted to hear and see more of there thoughts as a product designer.

being able to design is not just about designing a chair and then sombody sits down on it,

it's the thought and ideas that go into the chair before the design.

For example who is the chair for?

where is the chair going to be after it's designed?

What material makes a good strong chair?

The look of the chair, (style) is it for a hair salon?

What colour is the chair?

Is it for a child or adult? female or male?

These options have to all take place and that is what this program was all about.

Interactive media design

In terms of Interactive media design, where does all this fit in.

During the video he gave the students a project, the project was to goto a large store and bring back 2 products that represent, 1 of the following Function, gender or ecology.

He chose this project because he wanted to understand how they understand.

When designing for the web, we also have to design a online product for users to function with,

From watching the video we can use his research methods in the same way, for example, instead of going to a shop and buying products, as web designers we can simply go on the Internet and look at sites for inspiration.

we can take screen shots of sites that might come in handy for our own development,

By looking at others work will help us think about the design, just like the the students did in the store.

The Chair rule applies for us webdesigners too!

who is the website for?

where is the website going to be after it's designed? = internet

What content makes a good strong website?

The look of the website, (style) is it for a portfolio webpage?

What colour is the website?

Is it for a child or adult? female or male?

So this method applies to not just product designs but to all designers.

By Lee Blair.