8 months ago on September 3
Download free source files for this article. Example

MP3 Player

Here's the structure of a basic Flash MP3 player. Song information is retrieved from the file itself through its ID3 tags. For the most part, all functionality is written with ActionScript. There are also drawn components such as the Movie Clip bar fills, which use the ColorTransform class to dynamically alter its color.

Finding the Sound's Length

Getting the sound's length can be a bit tricky. If you use sound.length it will return the sound length of what's loaded only, so you won't know the total length until it has finished loading. You can use sound.id3.TLEN (if available) to get the total sound length since the ID3 information loads almost instantly. However, if the length isn't available from ID3 you can attempt to calculate it based on what's loaded with sound.bytesTotal*sound.length/sound.bytesLoaded.

Options

Basic variables at the top define functionality properties of the player.

var autoPlay = false; // Play as soon as not buffering
var loop = true; // Loop file when finished playing
var soundFile:String = 'sound.mp3';
var albumArt:String = 'album.jpg';

Upon hitting pause, the play position and volume level are stored in variables so that hitting play will continue in the same spot.

var currPos:uint = new uint(0);
var currVol:Number = new Number(1);
Setting Bar Colors with Hex

These are some colors I have chosen which I set by modifying the default black color of the movie clip with the colorTransform class. For the stream scrubber, I chose the the Hex color #EC7600. For the volume scrubber I chose #D955C1.

// START COLORS
var audioBarColor:ColorTransform = new ColorTransform();
audioBarColor.color = 0xEC7600;
mcAudioScrubber.mcFill.transform.colorTransform = audioBarColor;
 
var volBarColor:ColorTransform = new ColorTransform();
audioBarColor.color = 0xD955C1;
mcVolScrubber.mcFill.transform.colorTransform = audioBarColor;
// END COLORS
Setting Bar Colors with RGB

You can also set colors via RGB values. We'll add some fun by generating random colors when the user clicks the color button.

mcAudioScrubber.mcFill.transform.colorTransform = randColorTransform();
mcVolScrubber.mcFill.transform.colorTransform = randColorTransform();
function randColorTransform() {
	var r:uint = Math.round(Math.random()*255);
	var g:uint = Math.round(Math.random()*255);
	var b:uint = Math.round(Math.random()*255);
	return new ColorTransform(1, 1, 1, 1, r, g, b);
}

The Sound Class

In order to load our MP3 and retrieve its ID3 information we use the Sound class. Note that the file will load as soon as the URL Request is passed to the Sound class, as in the first line below. If no value is passed, the file will load upon calling the load method: sound.load(new URLRequest('sound.mp3')).

var sound:Sound = new Sound(new URLRequest('sound.mp3'));
sound.addEventListener(ProgressEvent.PROGRESS, progressing);
sound.addEventListener(Event.ID3, id3);
sound.addEventListener(Event.COMPLETE, completed);
function progressing(e:ProgressEvent):void {
	// Actions to be called as the file loads..
}
function id3(e:Event):void {
	// Actions to be called once ID3 information is available from the file..
}
function completed(e:Event):void {
	// Actions to be called once the file has loaded..
}
Buffering Check

Buffering happens when you're playing a file and you reach a certain point where no more data has been loaded yet. So the player pauses for a bit so that enough data can be loaded further for it to keep playing.

addEventListener(Event.ENTER_FRAME, bufferCheck);
function bufferCheck(e:Event):void {
	if(sound.isBuffering) {
		// Actions while the sound is buffering.. [Buffering, Please Wait]
	} else {
		// Actions while the sound is not buffering.. [Not Buffering]
	}
}
Loading the Album Art

In this case we just use an instance of the Loader class.

var albumArt:String = 'album_art.jpg';
var loader:Loader = new Loader();
loader.load(new URLRequest(albumArt));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
function loaded(e:Event):void {
	var content = e.target.content;
	addChild(content); // Add the content to the stage
}

ID3 Information

Trimming the Title

We can set a maximum of twenty characters for the title, trimming off the rest and adding periods.

var songName = sound.id3.songName;
if(songName.length > 20) {
	songName = songName.substr(0, 20)+'...';
}
Retrieving the Genre

Genres are passed as integers. For example, Alternative would be passed as (20). We can make a function to get the integer and match it to an array of genres (from ID3.org).

var genre = get_genre(sound.id3.genre);
function get_genre(val) {
	val = val.toString();
	val = val.replace(/\D/g, '');
	if(val == '') {
		return false;
	}
	var genres:Array = new Array('Blues', 'Classic Rock', 'Country', 'Dance', 'Disco', 'Funk', 'Grunge', 'Hip-Hop', 'Jazz', 'Metal', 'New Age', 'Oldies', 'Other', 'Pop', 'R&B', 'Rap', 'Reggae', 'Rock', 'Techno', 'Industrial', 'Alternative', 'Ska', 'Death Metal', 'Pranks', 'Soundtrack', 'Euro-Techno', 'Ambient', 'Trip-Hop', 'Vocal', 'Jazz+Funk', 'Fusion', 'Trance', 'Classical', 'Instrumental', 'Acid', 'House', 'Game', 'Sound Clip', 'Gospel', 'Noise', 'AlternRock', 'Bass', 'Soul', 'Punk', 'Space', 'Meditative', 'Instrumental Pop', 'Instrumental Rock', 'Ethnic', 'Gothic', 'Darkwave', 'Techno-Industrial', 'Electronic', 'Pop-Folk', 'Eurodance', 'Dream', 'Southern Rock', 'Comedy', 'Cult', 'Gangsta', 'Top 40', 'Christian Rap', 'Pop/Funk', 'Jungle', 'Native American', 'Cabaret', 'New Wave', 'Psychadelic', 'Rave', 'Showtunes', 'Trailer', 'Lo-Fi', 'Tribal', 'Acid Punk', 'Acid Jazz', 'Polka', 'Retro', 'Musical', 'Rock & Roll', 'Hard Rock', 'Folk', 'Folk-Rock', 'National Folk', 'Swing', 'Fast Fusion', 'Bebob', 'Latin', 'Revival', 'Celtic', 'Bluegrass', 'Avantgarde', 'Gothic Rock', 'Progressive Rock', 'Psychedelic Rock', 'Symphonic Rock', 'Slow Rock', 'Big Band', 'Chorus', 'Easy Listening', 'Acoustic', 'Humour', 'Speech', 'Chanson', 'Opera', 'Chamber Music', 'Sonata', 'Symphony', 'Booty Bass', 'Primus', 'Porn Groove', 'Satire', 'Slow Jam', 'Club', 'Tango', 'Samba', 'Folklore', 'Ballad', 'Power Ballad', 'Rhythmic Soul', 'Freestyle', 'Duet', 'Punk Rock', 'Drum Solo', 'A capella', 'Euro-House', 'Dance Hall');
	var genre = genres[val];
	if(genre != '') {
		return genre;
	}
	
	return false;
}

Playing, Stopping, and Setting the Volume

These actions are each called by one line, but other things need to happen as well so we'll create our own functions to handle these requests.

Play
function playSound(gouint = 0):void {
	stopSound(); // Stop so we don't get multiple audios playing
	addEventListener(Event.ENTER_FRAME, playing); // Update playing bar each frame, etc.
	soundChannel = sound.play(goTo); // Play sound through the soundChannel class
	soundChannel.addEventListener(Event.SOUND_COMPLETE, finishedPlaying);
	setVol(currVol); // If volume is reset when we stopped the sound, restore it
	playBtn.visible = false;
	pauseBtn.visible = true;
}
Stop
function stopSound():void {
	soundChannel.stop();
	removeEventListener(Event.ENTER_FRAME, playing);
	playBtn.visible = true;
	pauseBtn.visible = false;
}
Set the Volume
function setVol(vol:Number = 1):void {
	currVol = vol;
	soundTrans.volume = vol;
	soundChannel.soundTransform = soundTrans;
	//txtVol.text = Math.round(soundTrans.volume*100)+'%';
}

The Player

E-Mail RSS