import flash.events.MouseEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.net.URLRequest;
import flash.display.SimpleButton;
import flash.events.Event;
var bgmList:Vector.<String> = new <String>
[
"https://website.com/Beat_Your_Competition.mp3",
"bgm/Bounce_House.mp3",
"bgm/Chess_Pieces.mp3"
];
var sound:Sound;
var sChannel:SoundChannel;
var sTransform:SoundTransform;
var channelPosition:Number = 0;
var playing:Boolean = false;
var paused:Boolean = false;
var currentSound:int = -1;
function onMouse(e:MouseEvent):void
{
if (e.type == MouseEvent.CLICK)
{
if (e.currentTarget.parent == soundButtons)
changeSound(e.currentTarget as SimpleButton);
else if (e.currentTarget.parent == controlButtons)
{
if (e.currentTarget == controlButtons.pauseButton)
pauseSound();
else if (e.currentTarget == controlButtons.playButton)
playSound(channelPosition);
else if (e.currentTarget == controlButtons.stopButton)
stopSound();
}
controlStates();
}
}
function changeSound(button:SimpleButton):void
{
currentSound = int(button.name.slice(5, button.name.length));
channelPosition = 0;
nowPlaying.text = "Current song = " + bgmList[currentSound].split("/").pop();
if (playing)
{
sChannel.stop();
playSound(channelPosition);
}
}
function pauseSound():void
{
if (playing)
{
channelPosition = sChannel.position;
sChannel.stop();
playing = false;
paused = true;
}
}
function playSound(start:Number = 0, volume:Number = 1, loops:int = 0):void
{
if (currentSound == -1)
return;
if (sChannel)
sChannel.stop();
sound = new Sound();
sTransform = new SoundTransform();
sound.load(new URLRequest(bgmList[currentSound]));
sChannel = sound.play(start, loops);
sTransform.volume = volume;
sChannel.soundTransform = sTransform;
playing = true;
paused = false;
}
function stopSound():void
{
if (sChannel)
{
sChannel.stop();
channelPosition = 0;
playing = false;
paused = false;
}
}
function controlStates():void
{
if (playing)
{
progress.visible = true;
bar.visible = true;
controlButtons.pauseButton.alpha = 1;
controlButtons.stopButton.alpha = 1;
}
else
{
controlButtons.pauseButton.alpha = 0.35;
if (!paused)
{
progress.visible = false;
bar.visible = false;
controlButtons.stopButton.alpha = 0.35;
}
}
}
function enterFrameHandler(e:Event):void
{
if (playing)
{
if (sound.length > 0)
progress.scaleX = sChannel.position / sound.length;
}
}
function start():void
{
stop();
for (var i:int = 0, total:int = soundButtons.numChildren; i < total; i++)
soundButtons.getChildAt(i).addEventListener(MouseEvent.CLICK, onMouse);
for (i = 0, total = controlButtons.numChildren; i < total; i++)
controlButtons.getChildAt(i).addEventListener(MouseEvent.CLICK, onMouse);
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
nowPlaying.text = "Current song = none."
controlStates();
}
start();