140 Intermediate Flash Compatibility: MX 2004 (Principles and ActionScript are the same in Flash MX / Flash 5 / Flash 4)
Written by: Rabid Lemming
Length: 2,460 words
Assumed Knowledge: Good knowledge of ActionScript and HTML or better still XML would help
Level: Medium
Note: This
tutorial has not yet been edited - so that I cannot be sure it is error free
or that the instruction are easy to follow. It will be edited soon. Thanks
- Phil.
The aim of the tutorial is to learn how stream music in flash and make your own flash player. This is the basic version and a more advanced one is on the way soon.
Download All The Files You Need Here: Download140a
I only got one track to play because I don’t have any songs that I can play on the internet for free with out breaching copyright laws or paying royalties.
NOTE: Please remember if you play music on the internet you must ensure you have the legal copy write for it for have permission to play it. You can be charges royalties or legal action taken against you if you get court playing music that is not your own. It is illegal to share, play or distraught music with out prier consent/permission or acknowledgment of the person or persons who own the rights to that music. So if you do ignore this warning as I am sure many of you will, then you do so at your own risk and I have warned you. The music used for this tutorial is copy write of ministry of sound. http://www.ministryofsound.com
Give the player above a try. Please note how the next and previous buttons work and what happens when a track ends.
This simple player boast the following features:
It will play through all the tracks and albums automatically, going back to the start when finishing the last album track
The next and previous buttons allow you to skip through tracks and albums
Better coding than before. if you used this tutorial before i recommend you update your flash files as the improvements in this are much better
Set one: Set Up
Open up your flash movie
Click file publish setting
Click the flash tab
Select action script 6, action script version 2 (not 1)
Or select action script 7, action script version 2 (not 1)
Then click ok and return to the main stage
Add the preloader component to the stage.
Add a new layer, on frame 1 of the new layer add this code (Leave out any code hints you like, that the parts in red):
// Create a listener object event function. The progress bar is an object so needs an object function to work myProgressBarListener = new Object();
// When the progress bar is complete and has preloaded this movie, the listener will call and run this code below: myProgressBarListener = function (eventObject) {
// Hide the progress bar now as we don’t need it any more myProgressBar._visible = false;
// Un-comment any of the bellow code if you wish to use it instead:
// This will go to the next frame but may not automatically play beyond the next frame:
// nextFrame();
// This will go to the next scene but may not automatically play beyond the first frame in the next scene:
// nextScene();
// Replace the X with the frame number or label you want the movie to got. When referring to frame labels ensure that the label name is in quotes in the code. example:
// gotoAnd...("MyLableName");
// Go to and stop at the next frame. X is the frame number you want to movie to go to and stop at:
// gotoAndStop(X);
// Go to and play the next frame. X is the frame number you want to movie to go to and play.
// This will automatically play every frame after the value of X (the frame number you want the movie to go to and play) until it reaches a stop command:
// gotoAndPlay(X)
// In this example I have used the gotoandstop(); command because I want the movie to go to and stop at frame 2 gotoAndStop(2);
};
// Declares a listener that detects when the progress component has loaded the movie and is complete. Then calls the function myProgressBarListener myProgressBar.addEventListener("complete", myProgressBarListener);
// Set up the progress bar component variables myProgressBar.mode = "polled";
// Set up the progress bar component to polled when loading the movie. This will give a polled look to the progress bar as it loads. It has to be set to polled to work myProgressBar.source = "_root";
// Set the location to load as this movie. myProgressBar.conversion = "1";
// Set the conversion to 1. This basically means the component divides the current and total values loaded and to be loaded. Then it floors them (works out he difference between them) and displays the converted value in the label property myProgressBar.label = "LOADING %3%%";
// Set the label to display the word 'loading' followed by the percentage value loaded so far myProgressBar.direction = "right";
// The direction the progress bar moves when loading myProgressBar.labelPlacement = "bottom";
// The location of the label that displays the percentage loaded so far stop();
// Stop the movie at the frame until the move has been preloaded
Then select the progress bar component on the stage and in the property panel give it an instance name: myProgressBar
Set Two: Set Up The Player
Create a new movie clip called "mover"
Ensure that in the property panel for that movie clip it has the instance name: mover
Open up the Movie Clip
Inside that movie clip on frame 1 add this code:
// Change the value of this variable _root.CallerCheck = 0;
// Stop this movie clip at the current frame stop();
Select frame 3 and insert a key frame
In frame 3 add this code:
// Call this function Caller(); // Check this variable value if (_root.CallerCheck == 1) { // If this variable is equal to one go to and stop at frame 1 gotoAndStop(1); // If this variable is not equal to one } else { // Then go to and play from frame 2 gotoAndPlay(2);
}
Return to the main stage and ensure to give the movie clip in the property panel
Create a shape like this
The shape should be big enough that when place over the player it covers the controls of the player.
Position the shape over the player to ensure it properly covers the player controls and write down the x and y values.
In my example, my x and y values were:x = 13.4, y = 257.3
This is so that when the player is loading, it stops the user from pressing any of the player buttons till the player is ready, like so:
Convert the shape to a button
Open the button clip up and ensure that they shape is in the hit state only like so:
Return to the stage and give the button the instance name in the property panel of: Mask
Position the button off the stage out the way
When the player is loading data. You don't want the user pressing buttons and trying to play any music till the player is ready
So we use this button and position it over the player to cover the controls.
The code move this button in over the player till it is ready for use then moves it out the way when it is ready for use by the user.
This is important as if the user presses the player buttons before its ready it will cause problems and may not work properly
In the code just below look for: var maskX = see notes above; and var maskY = see notes above;
This sets the location of the button mask for when it is over the player. This is where you set the maskX variable value to the x location of the shape that you wrote down in step 11 above and the same goes for maskY
So in my example my code below would be:
var maskX = 13.4;
var maskY = 257.3;
You need to do this as your x and y values may be different to mine depending on how you position your player and its size and etc..
Set Two: Set Up The Player Code
Add this code to a layer on frame 2 of the movie (You may miss out the comments in read if you wish but read the notes above!!!):
// Declare variables var maskX = see notes above;
var maskY = see notes above;
// ================================================================== \\
// MY EXAMPLE ONLY !!!
// Just to show you how it should look but DO NOT use these values for your movie !!!
// Read the notes above !!!!
// var maskX = 13.4;
// var maskY = 257.3;
// =================================================================== \\ var already = 0;
var CallerCheck = 0;
var ready = "0";
var position = 1;
var me = "";
var started = "false";
//-------for myComboBox-----------\\
// Set the create a xml object above var mycomboXml = new XML();
// When the xml object has loaded run this function mycomboXml.onLoad = function() {
//-------firstChild-----------\\
// Read-only property; evaluates the specified XML object and references the first
// Child in the parent node’s child list. This property is null if the node does not have children.
// This property is undefined if the node is a text node. This is a read-only property and cannot be used to manipulate child nodes;
//-------childNodes-----------\\
// Read-only property. An array of the specified XML object’s children. Each element in the array is a reference to an XML object that
// Represents a child node. This is a read-only property and cannot be used to manipulate child nodes
//-------Basic Term-----------\\
// Get the number of items or tracks from the xml file and set the value of the variable to that number var baseName = this.firstChild.childNodes;
// Declare variables var albumName;
var xmlFile;
// Set up a for loop for the number of tracks in the xml file for (var j = 0; j<baseName.length; j++) {
// Checks each track has a name and location if (baseName[j].nodeName != null) {
// Get the track name from the xml file albumName = baseName[j].attributes.albumName;
// Get the track location xmlFile = baseName[j].attributes.xmlFile;
// Add the information to the combo box myComboBox.addItem({label:baseName[j].attributes.albumName, data:baseName[j].attributes.xmlFile});
// Trace what’s just happened trace("myalbum for label: "+baseName[j].attributes.albumName+" /for data: "+baseName[j].attributes.xmlFile);
}
}
// Only run this code once for when the movie fist loads. This function automatically loads the songs from the first album into the list box if (already == 0) {
// Set the variable so that this code wont be run again already = 1;
// Call global runme function runme(); }
};
// Load the xml page data into the combo box mycomboXml.load("mycombodata.xml");
//--------for listBox------------
// Set up an array myArry = new Array();
// Set up an xml object xmlName = new XML();
// Ignore or disregard any empty enters in the xml page xmlName.ignoreWhite = true;
// When the xml page has been loaded run this code xmlName.onLoad = function() {
// Update the list box scroll bar to account for the new list myListBox.vScrollPolicy = "on";
// Trace the fact that the load event has been successful trace("xmldata loaded success!");
// Get the number of items or tracks from the xml file and set the value of the variable to that number var baseNode = this.firstChild.childNodes;
// Set up variables var mylabel, mydata, link;
// Set up a for loop for the number of tracks in the xml file for (var i = 0; i<baseNode.length; i++) {
// Checks each track has a name and location if (baseNode[i].nodeName != null) {
// Get the track titles and set their names to each variable mylabel = baseNode[i].attributes.mylabel;
mydata = baseNode[i].attributes.mydata;
// Add the variables values to the list box myListBox.addItem({label:mylabel, data:mydata});
// Display what has been added trace("My XmldataList labelList: "+baseNode[i].attributes.mylabel+" databList: "+baseNode[i].attributes.mydata); }
// Set the array to hold to hold the values from the variables myArray.push(new construct(mylabel, mydata, link));
}
};
// Conversion function; creates a new empty object or converts the specified number, string, or Boolean value to an object. This command is equivalent to creating an object using the Object constructor var myPlayBackListener = new Object();
// If the play button is click the listener will pick it up and run this function myPlayBackListener.click = function() {
// Works out if any track has been selected if (_root.title == "no tracks selected") {
// If no track has been selected don’t allow playing _root.title = "Please select a track to play";
// Stop the media player from playing myPlayBack.stop(); }
};
// If the play button is click the listener will pick it up and run the function above myPlayBack.addEventListener("click", myPlayBackListener);
//-----------myListBox Event-------------
// Conversion function; creates a new empty object or converts the specified number, string, or Boolean value to an object. This command is equivalent to creating an object using the Object constructor myselection = new Object();
// This function is run when the listener picks up if a song in the list box has been selected myselection.change = function(ListEvent) {
// Show the status movie clip _root.status._visible = 1;
// Set the media player to play the selected song from the list box myPlayBack.setMedia(myListBox.selectedItem.data, "MP3");
// Set the play back to the start myPlayBack.playheadTime = 1;
// Set the music player to play the song from the start myPlayBack.play(1);
// Set the text box title to the name of the track elected _root.title = myListBox.selectedItem.label;
// Trace what’s happened trace("the selected trackPath: "+myListBox.selectedItem.data);
};
// Listener for the combo box calls the above function when the combo box selection is changed. myListBox.addEventListener("change", myselection);
//----------comboBox Event---------
// Conversion function; creates a new empty object or converts the specified number, string, or Boolean value to an object. This command is equivalent to creating an object using the Object constructor mycomboSelect = new Object();
// This function is run when the listener picks up if the combo box selection has been changed mycomboSelect.close = function() {
// This function loads the xml data to get the songs in the chosen album to display in the list box
// Set xml path xmlPath = "mylistdata.xml";
// Get the combo box selected item xmlPath = myComboBox.selectedItem.data;
// Load the xml page data for the player xmlName.load(xmlPath);
// Clear the list box myListBox.removeAll();
// Stop the play head myPlayBack.stop();
// Tell the user no track has been selected _root.title = "no tracks selected";
// Hide the status movie clip _root.status._visible = 0;
// Set the media player to play any song selected in the play list myPlayBack.setMedia(myListBox.selectedItem.data, "MP3");
// Trace what’s happened trace("myAlbumSelection: "+xmlName+"/data: "+xmlPath);
};
// Listener for the combo box calls the above function when the combo box selection is changed. myComboBox.addEventListener("close", mycomboSelect);
// Global function _global.runme = function() {
// This function loads the xml data to get the songs in the chosen album to display in the list box
// Set xml path xmlPath = "mylistdata.xml";
// Get the combo box selected item xmlPath = myComboBox.selectedItem.data;
// Load the xml page data for the player xmlName.load(xmlPath);
// Clear the list box myListBox.removeAll();
// Stop the play head myPlayBack.stop();
// Tell the user no track has been selected _root.title = "no tracks selected";
// Hide the status movie clip _root.status._visible = 0;
// Set the media player to play any song selected in the play list myPlayBack.setMedia(myListBox.selectedItem.data, "MP3");
// Trace what’s happened trace("myAlbumSelection: "+xmlName+"/data: "+xmlPath);
};
// Hide the track tile _root.tracktitle._visible = 0;
// Conversion function; creates a new empty object or converts the specified number, string, or Boolean value to an object.
// This command is equivalent to creating an object using the Object constructor var myProgressListener = new Object();
// Function run by listener event below myProgressListener.progress = function() {
// Work out the bytes loaded so far _root.status.myloaded = Math.round(myPlayBack.bytesLoaded/1000);
// Work out the total bytes to load _root.status.total = Math.round(myPlayBack.bytesTotal/1000);
};
// This listener picks up the progress of the music been streamed myPlayBack.addEventListener("progress", myProgressListener);
// Conversion function; creates a new empty object or converts the specified number, string, or Boolean value to an object.
// This command is equivalent to creating an object using the Object constructor var myFinnishListener = new Object();
// This function is called when the track playing has finished or reached the end myFinnishListener.complete = function(eventObject) {
// Check to see if the player selects the next track in the album, if the that next track is the last track available in that album if (myListBox.selectedIndex+1 == myListBox.length) {
// If the next selected in the album is the last track available in that album run the following if statements if (myComboBox.selectedIndex == undefined) {
// If no album is selected select then select the first album myComboBox.selectedIndex = 0;
// Change the value of this variable position = 1;
// Call this function caller3();
// Check to see if their is another album available or if the list of albums is at the end } else if (myComboBox.selectedIndex+1 == myComboBox.length) {
// If the list of albums is at the end go to and load the first album myComboBox.selectedIndex = 0;
// Change the value of this variable position = 1;
// Change the value of this variable ready = "1";
// Call this function caller3();
// If their is another album available then load it } else {
// If another album is available then load it myComboBox.selectedIndex = myComboBox.selectedIndex+1;
// Change the value of this variable ready = "1";
// Change the value of this variable position = 1;
// Call this function caller3();
}
// If there are more previous tracks available in the current album then run the following } else {
// If the next track in the current album is not the last track then check that their is a track selected for the album if (myListBox.selectedIndex == undefined) {
// If no track is selected select then select the first track in the current album myListBox.selectedIndex = 0;
// Change the value of this variable position = 1; // Call this function caller3();
// If a track has been selected and their is a previous track available then select it } else {
// If the next track in the current album is not the last track then load that track myListBox.selectedIndex = myListBox.selectedIndex+1;
// Change the value of this variable position = 2;
}
// Stop the movie clip 'myPlayBack' myPlayBack.stop();
// Call this function wait();
}
};
// When the current track playing has finished or reached the end call the function 'myFinnishListener' myPlayBack.addEventListener("complete", myFinnishListener);
// Define A function function wait() {
// Alert the user to wait _root.title = "Please wait...";
// If the player is waiting for the albums and track to load move a mask to
// stop the user from trying to play any tracks before they are properly loaded this.Mask._x = maskX;
this.Mask._y = maskY;
// Call the function caller2 after 1 second
// A delay is needed to allow time to load the new data for the next song into the player myTimer = setInterval(Caller2, 1000);
}
// Conversion function; creates a new empty object or converts the specified number, string, or Boolean value to an object.
// This command is equivalent to creating an object using the Object constructor playheadChangelistener = new Object();
// This function is called when the next or previous buttons are pressed playheadChangelistener.playheadChange = function(eventObject) {
// Set the variable me to the percentage played so far me = eventObject.detail;
// If the percentages played is 0 then the user has pressed the previous button and want to play the previous track. Their for run this code below if (me == 0) {
// Clear the variable value me = "";
// Check to see if the player can select the previous track in the album or if their are no more previous tracks available in the current album if (myListBox.selectedIndex-1<0) {
// if their are no more previous tracks available in the current album then run the following if statements if (myComboBox.selectedIndex == undefined) {
// If no album is selected select then select the first album myComboBox.selectedIndex = myComboBox.length-1;
// Change the value of this variable position = 1;
// Call this function caller3();
// Check to see if their is a previous album available or if the list of albums is at the beginning } else if (myComboBox.selectedIndex-1<0) {
// If the list of albums is at the beginning go to and load the last album myComboBox.selectedIndex = myComboBox.length-1;
// Change the value of this variable ready = "1";
// Change the value of this variable position = 3;
// Call this function caller3();
// If it is possible to load the next album then do so } else {
// If a previous album is available then load it myComboBox.selectedIndex = myComboBox.selectedIndex-1;
// Change the value of this variable position = 3;
// Change the value of this variable ready = "1";
// Call this function caller3();
}
// If there are more tracks available in the current album then run the following } else {
// If the previous track in the current album is not the first track then check that their is a track selected for the current album if (myListBox.selectedIndex == undefined) {
// If no track is selected select then select the first track in the current album myListBox.selectedIndex = 0;
// Change the value of this variable position = 1;
// Call this function caller3();
// If it is possible to load the next track then do so } else {
// If the previous track in the current album is not the last track then load the previous track to the currently selected track myListBox.selectedIndex = myListBox.selectedIndex-1;
// Change the value of this variable position = 2;
}
// Stop the movie clip 'myPlayBack' myPlayBack.stop();
// Call this function wait();
}
// If the player has just started for the first time and the user presses the next button select the first track in the current album } else if (started == "false") {
// Change the value of this variable started = "";
// If the next track in the current album is not the last track then check that their is a track selected for the album if (myListBox.selectedIndex == undefined) {
// If no track is selected select then select the first track in the current album myListBox.selectedIndex = 0;
// Change the value of this variable position = 1;
// Call this function caller3();
// Stop the movie clip 'myPlayBack' myPlayBack.stop();
// Call this function wait();
}
}
};
// When the users presses the next or previous track buttons call the function 'playheadChangelistener' myPlayBack.addEventListener("playheadChange", playheadChangelistener);
// Define A function function caller3() {
// This function loads the xml data to get the songs in the chosen album to display in the list box
// Set xml path xmlPath = "mylistdata.xml";
// Get the combo box selected item xmlPath = myComboBox.selectedItem.data;
// Load the xml page data for the player xmlName.load(xmlPath);
// Clear the list box myListBox.removeAll();
// Stop the play head myPlayBack.stop();
// Tell the user no track has been selected _root.title = "no tracks selected";
// Hide the status movie clip _root.status._visible = 0;
// Set the media player to play any song selected in the play list myPlayBack.setMedia(myListBox.selectedItem.data, "MP3");
// Trace what’s happened trace("myAlbumSelection: "+xmlName+"/data: "+xmlPath);
// Tell this movie clip to and play from frame 2 _root.mover.gotoAndPlay(2);
}
// Define A global function _global.Caller = function() {
// Show the status movie clip _root.status._visible = 1;
// Set the media player to play the selected song from the list box myPlayBack.setMedia(myListBox.selectedItem.data, "MP3");
// Set the play back to the start myPlayBack.playheadTime = 1;
// Set the music player to play the song from the start myPlayBack.play(1);
// Set the text box title to the name of the track elected _root.title = myListBox.selectedItem.label;
// Trace what’s happened trace("the selected trackPath: "+myListBox.selectedItem.data);
// Set this variable to 1 so that movie clip wont keep playing and calling this function CallerCheck = 1;
// Runs a check on the variable 'ready' if (ready == "1") {
// Change this variable value ready = "0";
// Stop the player from playing myPlayBack.stop();
// Call this function wait();
}
};
// Define A global function _global.Caller2 = function() {
// Check this variable and set the selected track according to the variable value if (position == 1) {
// If this variable is equal to 1 then select the first track in the list of tracks available for the current album myListBox.selectedIndex = 0;
} else if (position == 2) {
// If this variable is equal to 2 then do nothing as the track has already been selected from the previous function } else if (position == 3) {
// If this variable is equal to 3 then select the last track in the list of tracks available for the current album myListBox.selectedIndex = myListBox.length-1;
}
// Move the mask out the way so the user can user the player controls _root.Mask._x = 999;
_root.Mask._y = 999;
// Show the status movie clip _root.status._visible = 1;
// Set the media player to play the selected song from the list box myPlayBack.setMedia(myListBox.selectedItem.data, "MP3");
// Set the play back to the start myPlayBack.playheadTime = 1;
// Set the music player to play the song from the start myPlayBack.play(1);
// Set the text box title to the name of the track elected _root.title = myListBox.selectedItem.label;
// Trace what’s happened trace("the selected trackPath: "+myListBox.selectedItem.data);
// Stop the timer function clearInterval(myTimer);
};
Set Three: Requirements
You MUST have the following ( you don't have to have flash MX 2004 professional, that is only if you want the Flash Video Exporter. You must have at least flash MX 2004) :
Macromedia Video Kit
Get the Macromedia Video Kit, which includes:
A Flash Video extension for Dreamweaver
A special version of Sorenson Squeeze for converting video to Flash Video (FLV) format
Install the flash video player exe (run the "Flash_Video_Exporter.exe" file from the winzip file)
Install the flash media components (run the "MediaComponents.mxp" file from the winzip file)
restart your pc (recommended)
Load flash
Get the media player components from the component library and drag it to your stage.
Highlighted in blue here:
Set Four: Adding the component
Give the component the instance name: myPlayBack
You should see this:
Then in the property inspector click: Launch Component Inspector
Then make sure the following options are selected like below:
Set Five: Adding additional parts
Create a text box with the var name: title
Create another text box with the var name: mybuffer
Add the list box component from the component
library
to the stage and give it the instance name: myListBox
Create a move clip with the instance name : status
Ensure that in the property panel for that movie clip it has the instance name: mover
Open up the movie clip
Inside the movie clip and add a text box with var name: myloaded
Add another text box inside the movie clip with var name: total
Return to the stage and
position
the text box's like in the image below
You should have something like this (each text box has text in it to identify what text box var name is so you know were to place the text box's and the list box component)
Set Five: Do some tweaking and it should finally look like this:
Set Six: The XML code set up
Create XML web page with this code:
(You can customize this however you like by changing the album titles.
As well as changing the number of albums you have. You can change the location and file name of the XML files containing the
album songs but I don't recommend it unless you know what your doing)
I recommend you leave out the comments. That's the lines in gray.
<!--
open tag
//--> <xmlPath> <!--
Set the album name and name of xml containing the list of songs for that album
//--> <myPath albumName="Classical" xmlFile="mylistdata1.xml"> <!--
close tag
//--> </myPath> <!--
Set the album name and name of xml containing the list of songs for that album
//--> <myPath albumName="Rock 'n Roll" xmlFile="mylistdata2.xml"> <!--
close tag
//--> </myPath> <!--
close tag
//--> </xmlPath>
Save the page as: mycombodata.xml
Create another XML web page with this code:
(You can customize this however you like by changing the song titles.
As well as changing the number of songs you have. You can change the location and file name of the song files containing)
<!--
open tag
//--> <database> <!--
set the song name and location
//--> <Index mylabel="Song 1" mydata="http://www.YourWebSite.com/Song1.mp3"> <!--
Close tag
//--> </Index> <!--
set the song name and location
//--> <Index mylabel="Song 2" mydata="http://www.YourWebSite.com/Song2.mp3"> <!--
Close tag
//--> </Index> <!--
set the song name and location
//--> <Index mylabel="Song 3" mydata="http://www.YourWebSite.com/Song3.mp3"> <!--
Close tag
//--> </Index> <!--
Close tag
//-->
Save the file as: mylistdata1.xml
Do the same again for: mylistdata2.xml and the rest of the xml files for your albums. I think you can probably work out how this works.
You can have as many albums and songs in each album as you like.
IMPORTANT: Remember to keep all the xml files in the same location as your swf movie