I created a basic audio player. It’s purpose is to play one sound file, not as music player but to play instructions for a lesson. It has the play, pause, stop and scrub functionalities.
It all works, but the scrub bar is not draggable, but clickable.
Here’s the source files
Below’s the as3 script with comments included.
//define variables
var clipSnd:Sound = new Sound (new URLRequest("ff2.mp3"));//load sound
var clipCnl:SoundChannel;//create soundchannel
var clipTmr:Timer = new Timer(1000);//create a timer with timerevent per second
var playTime:Number = 37;//the lenght of the mp3, too much fuss to calculate when using only one file
var isPlaying:Boolean = false;
var newPos:Number;
var curPos:Number = 0;
var tmrDuration:Number = 0;
//var nessecary for scrubbar in CS3
//in CS5 use the scaleX option, dunno if this is also possible in CS4
var barTotalWidth = 275;
var barStartWidth = 0;
//define functions
function playMusic(event:MouseEvent):void {
if (!isPlaying) {
clipCnl = clipSnd.play(curPos);
if (clipTmr.running != true) {
clipTmr.start();
}
}
isPlaying = true;
}
function pauseMusic(event:MouseEvent):void {
curPos = clipCnl.position;
clipCnl.stop();
isPlaying = false;
clipTmr.stop();
}
function stopMusic(event:MouseEvent):void {
resetMusic();
}
function scrubMusic(event:MouseEvent):void {
if (isPlaying) {
clipCnl.stop();
tmrDuration = Math.round((event.localX * playTime) / barTotalWidth);
newPos = tmrDuration * 1000;
slidermc.width = event.localX;
clipCnl = clipSnd.play(newPos);
//trace (event.localX);
}
}
function updateSlider(event:TimerEvent):void {
if (tmrDuration < playTime) {
tmrDuration++;
slidermc.width = Math.round((tmrDuration * barTotalWidth)/playTime);
tf.text = String(tmrDuration);
} else {
resetMusic();
}
}
function resetMusic():void {
clipTmr.stop();
curPos = 0;
clipCnl.stop();
isPlaying = false;
slidermc.width = barStartWidth;
tmrDuration = 0;
}
//initialize player
slidermc.width = barStartWidth;
clipCnl = clipSnd.play();
clipTmr.start();
isPlaying = true;
//set eventlisteners
playbtn.addEventListener(MouseEvent.CLICK, playMusic);
pausebtn.addEventListener(MouseEvent.CLICK, pauseMusic);
stopbtn.addEventListener(MouseEvent.CLICK, stopMusic);
scrubbtn.addEventListener(MouseEvent.CLICK, scrubMusic);
clipTmr.addEventListener(TimerEvent.TIMER, updateSlider);
//script by silvith
//on the topic of the length of the sound-file, there are 4 options:
//1. you can add this information to the ID3 tag and access it as mySound.id3.TLEN
//2. you can only use mySound.length when the file is completely loaded,
// so you need to check mySound.bytesLoaded against mySound.bytesTotal before using mySound.length
//3. you can import the length through flashvars, i.e. myswf.mp3?sndDur=23
//4. you can do as I did and simply fill in the number of seconds here.
// this limits the usage of the audio player to one file.