A designer I do some work for hired me to make a Music Player for a Flash web page. The requirements were to have the page start playing a song from frame 1 of the time line while an intro animation was playing. After the animation, there would be a button that allowed the user to play and pause a song. I chose to use the Singleton Design Pattern because frame one of the time line could create the instance, then a MovieClip Symbol could get the same instance later and call its functions without anything strange occurring (like the song playing again, while the first song played, also). The code is in the rest of the entry.
package {
import flash.net.URLRequest;
import flash.media.*;
import flash.events.Event;
public class MusicPlayer
{
private var soundReq:URLRequest;
private var sound:Sound;
private var soundControl:SoundChannel;
private var isPlaying:Boolean;
private static var _instance:MusicPlayer;
public function MusicPlayer(pvt:PrivateClass)
{
}
public static function getInstance():MusicPlayer
{
if(MusicPlayer._instance == null)
{
MusicPlayer._instance = new MusicPlayer(new PrivateClass);
}
return MusicPlayer._instance;
}
public function startMusic():void
{
sound = new Sound();
soundReq = new URLRequest("sounds/song.mp3")
sound.load(soundReq);
soundControl = sound.play();
isPlaying = true;
soundControl.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
}
public function handleClick():String
{
var pausePosition:int = soundControl.position;
if(isPlaying == true)
{
soundControl.stop();
isPlaying = false;
return 'play';
}
else
{
soundControl = sound.play(pausePosition);
soundControl.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
isPlaying = true;
return 'pause';
}
}
private function soundCompleteHandler(e:Event):void
{
// this makes the song play again from the beginning
soundControl = sound.play(0);
soundControl.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
isPlaying = true;
}
}
}
class PrivateClass
{
public function PrivateClass()
{
//trace('Music Player initialized');
}
}
To use this, all you need to do first is get it and start the music:
var musicPlayer:MusicPlayer;
musicPlayer = MusicPlayer.getInstance();
musicPlayer.startMusic();
And then from anywhere else you can get it by using:
var musicPlayer:MusicPlayer;
musicPlayer = MusicPlayer.getInstance();
var whatWillItDoNextTimeICallhandleClick:String = musicPlayer.handleClick();
You can use this code for your own personal growth and feel free to leave a comment!




