欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Flash播放器(基于actionScript3.0) Flash.net音乐XMLUP

程序员文章站 2022-06-06 15:14:08
...
闲来无事开发的一款个人播放器,预览地址:http://17446.2m2m.net/music/MediaPlayer.swf

源码:

package{
import flash.display.Sprite;
import flash.system.System;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.errors.IOError;
import flash.media.SoundLoaderContext;
import flash.events.Event;
import flash.events.MouseEvent;
    import flash.utils.setInterval;
import flash.utils.clearInterval;
import flash.utils.setTimeout;
    import flash.display.Graphics;
import fl.controls.Label;
import fl.controls.Button;
import fl.controls.Slider;
import fl.events.SliderEvent;

import flash.display.SimpleButton;
    import flash.geom.Rectangle;
import flash.text.TextField;
import flash.display.MovieClip;
import fl.managers.FocusManager;

/*
*** designed by Zhang Zhen;
*** 2009-09-15
*/

public class MediaPlayer extends Sprite{
//音乐列表
private const FILEPATH:String="";
private const musicListURL:String="musicList.xml";
private var musicListURLRequest:URLRequest;
private var musicListLoader:URLLoader;
private var musicXML:XML;
private var musicList:Array;
//歌词相关
private var lrcRequest:URLRequest;
private var lrcLoader:URLLoader;
private var lrcArray:Array;
private var timeOffset:Number=0;
private var lrcInterval:int=-1;

//声音相关

private var soundURLRequest:URLRequest;

    private var sound:Sound;
private var channel:SoundChannel;
private var soundLoaderContext:SoundLoaderContext;
private var soundTransForm:SoundTransform;


//组件相关

private var drapRectangle_Volumn:Rectangle;
private var drapRectangle_Progress:Rectangle;


//变量相关
private var play_tag:int=-1;
private var startPosition:int;
private var soundLength:int;
private var currentIndex:int=0;//当前播放歌曲所在索引
private var progressBarWidth:int=250;
private var musicNameStart:int=0;
private var musicNameInterval:int=-1;

private var soundAble:Boolean=true;
private var dragProgressSlider:Boolean=false;

public function MediaPlayer(){
trace("初始化");
    System.useCodePage=true;
Slider_Init();
Button_Init();
//初始化列表
MusicList_Init();
//初始化播放
    Player_Init();
//言辞一段时间
setTimeout(playMusic,2000);

}

private function Slider_Init():void{

  
   drapRectangle_Volumn= new Rectangle(-2,-10,48,0);
   drapRectangle_Progress= new Rectangle(-2,-7,progressBarWidth-2,0);
  
   slVolumn.Volumn_Silder.addEventListener(MouseEvent.MOUSE_DOWN,VolumnSliderHandler);
   slVolumn.Volumn_Silder.addEventListener(MouseEvent.MOUSE_UP,VolumnHandler);
   slVolumn.Volumn_Silder.addEventListener(MouseEvent.ROLL_OVER,VolumnHandler);
  
  
   progressBar.PlayedPosition.addEventListener(MouseEvent.MOUSE_DOWN,ProgressSliderHandler);
   progressBar.PlayedPosition.addEventListener(MouseEvent.MOUSE_UP,ProgressHandler);
   progressBar.PlayedPosition.addEventListener(MouseEvent.ROLL_OVER,ProgressHandler);
 

}
private function Button_Init():void{

btnPlay.addEventListener(MouseEvent.CLICK,Play_Click);
btnPause.addEventListener(MouseEvent.CLICK,Pause_Click);
btnStop.addEventListener(MouseEvent.CLICK,Stop_Click);
btnPrev.addEventListener(MouseEvent.CLICK,Prev_Click);
btnNext.addEventListener(MouseEvent.CLICK,Next_Click);
btnVolumn.addEventListener(MouseEvent.CLICK,Volumn_Click);


btnClose.addEventListener(MouseEvent.CLICK,Close_Click);

}
private function MusicList_Init():void{
  
musicList=new Array();
    musicListURLRequest=new URLRequest(FILEPATH+musicListURL);
    musicListLoader=new URLLoader();

musicListLoader.addEventListener("ioError",IOError_Handler);
musicListLoader.addEventListener(Event.COMPLETE,completeHandler);
    musicListLoader.load(musicListURLRequest);

}

private function Player_Init():void{
btnJinYin.visible=false;
soundURLRequest=new URLRequest();
soundLoaderContext=new SoundLoaderContext(1000,true);

soundTransForm=new SoundTransform();
soundTransForm.volume=1;

this.addEventListener(Event.ENTER_FRAME,onEnterFramed);


}
//音量
private function VolumnSliderHandler(_event:MouseEvent):void{

_event.currentTarget.startDrag(false, drapRectangle_Volumn);

}
    private function VolumnHandler(_event:MouseEvent):void{

_event.currentTarget.stopDrag();
}
//进度托动
private function ProgressSliderHandler(_event:MouseEvent):void{
dragProgressSlider=true;
_event.currentTarget.startDrag(false, drapRectangle_Progress);

}
    private function ProgressHandler(_event:MouseEvent):void{

if(dragProgressSlider){
  _event.currentTarget.stopDrag();
  dragProgressSlider=false;
  startPosition=((progressBar.PlayedPosition.x+2)/progressBarWidth)*soundLength;
// playMusic();
if(musicList!=null&&musicList.length>0){
  if(channel!=null)
      channel.stop();

     channel=sound.play(startPosition);
channel.soundTransform=soundTransForm;
 
}

}


}
private function IOError_Handler(_e:Event):void{
  musicListLoader=null;
  txtMusicName.text="加载列表失败!";
}
private function completeHandler(_e:Event):void{
//注意歌曲数组:如musicList[0][1] :地址,歌名

  var loader:URLLoader=URLLoader(_e.target);
  musicXML=XML(loader.data);
  for each(var music:XML in musicXML.music){
  var _temp:Array=new Array(music.url,music.name);
   musicList.push(_temp);
  }
if(musicList!=null&&musicList.length>0){
txtMusicName.text=musicList[0][1];
}
}
    private function LRC_IOError_Handler(_e:Event):void{
lrcLoader=null;
txtLrc.text="未找到相关歌词!";

}
//字串MM:ss转成秒
private function converToSeconds(_times:Array):Number{
  return Number(int(_times[0])*60+int(_times[1])+int(_times[2])/100)
}

private function analyseLrc(_result:String):Array{
//时间
var timesReg:RegExp=/\[\d{2}:\d{2}\.\d{2}\]/g;
var readTimeReg:RegExp=/\d{2}/g;

var timesAndLrcs:Array;
             var times:Array=new Array();
var lrcs:Array=new Array();
txtLrc.text="";
             var _lrcArray:Array=_result.split("\r\n");

for each(var line:String in _lrcArray){
  
   var tempTimeArray:Array=line.match(timesReg);
  
   //如果不是带时间线的歌词,则解析 标题,专辑等信息
   if(tempTimeArray==null||tempTimeArray.length==0){
  
   analyseLrcOther(line);
  };
   var lrc:String=line.replace(timesReg,"");

   for each(var _timer:String in tempTimeArray){
      var _readTimes:Number=converToSeconds(_timer.match(readTimeReg));
  times.push(_readTimes);
  lrcs.push(lrc);
   }

}

  timesAndLrcs=new Array(times,lrcs);

  return timesAndLrcs;
}
private function analyseLrcOther(line:String):void{

  line=line.replace("[","");
  line=line.replace("]","");
  var tiArray:Array=line.split("ti:");
  var arArray:Array=line.split("ar:");
  var alArray:Array=line.split("al:");
  var offSetArray:Array=line.split("offset:");
  if(tiArray!=null&&tiArray.length>1){
  txtLrc.htmlText="<font color='#ff0000'>标题:</font>"+tiArray[1];
  }
  if(arArray!=null&&arArray.length>1){
  txtLrc.htmlText+="<font color='#ff0000'> 作者:</font>"+arArray[1];
  }
   if(alArray!=null&&alArray.length>1){
  txtLrc.htmlText+="<font color='#ff0000'> 专辑:</font>"+alArray[1];
   }
   if(offSetArray!=null&&offSetArray.length>1){
  var _t:String=offSetArray[1];
  timeOffset=Number(int(_t)/1000);

   }

}
private function LRC_completeHandler(_e:Event):void{
txtLrc.text="正在解析...";
var loader:URLLoader=URLLoader(_e.target);
if(loader!=null){
var _result:String=loader.data;
lrcArray=analyseLrc(_result);
lrcArray.sortOn("0",Array.NUMERIC);

lrcInterval=setInterval(setLrcValue,500);
}
}
private function setLrcValue():void{
if(lrcArray!=null){

var _currentTime=Math.round(startPosition);

for(var i:int=0;i<lrcArray[1].length;i++){
  var temp:int=Math.round(lrcArray[0][i]+timeOffset);
 
if(temp==_currentTime)
     {
      var txt:String=lrcArray[1][i].toString();
  txtLrc.text=txt;
      break;
}
     
}
}
}
//开始,暂停,停止,前进,后退等

//设置歌曲名称效果

private function setMusicName(_name:String):void{
         var mName:String=_name;
var _length:int=_name.length;
mName=mName.substr(musicNameStart,_length-musicNameStart);
if(_length>0)
    musicNameStart=(musicNameStart+1)%(_name.length);
txtMusicName.text=mName;
}
//设置当前歌词
private function loadLrc(_lrcURL:String):void{
txtLrc.text="尝试加载对应歌词...";
lrcRequest=new URLRequest(_lrcURL);
lrcLoader=new URLLoader();
if(lrcInterval!=-1)
   clearInterval(lrcInterval);
lrcLoader.addEventListener("ioError",LRC_IOError_Handler);
    lrcLoader.addEventListener(Event.COMPLETE,LRC_completeHandler);
lrcLoader.dataFormat=URLLoaderDataFormat.TEXT;
lrcLoader.load(lrcRequest);

}
private function flushMediaPlayer():void{
var _musicName:String=musicList[currentIndex][1];

var lrcUrl:String=FILEPATH+_musicName+".txt";
loadLrc(lrcUrl);
musicNameStart=0;
if(musicNameInterval!=-1)
clearInterval(musicNameInterval);
musicNameInterval=setInterval(setMusicName,500,_musicName);

}
private function playMusic():void{

  play_tag=1;
  progressBar.AllData.width=0;
  txtTip.text="loading...";
  if(musicList!=null&&musicList.length>0){
  if(channel!=null)
      channel.stop();
 
  soundURLRequest.url=musicList[currentIndex][0];
 
  sound=new Sound(soundURLRequest,soundLoaderContext);
  sound.addEventListener("ioError",Sound_IOError_Handler);

  channel=sound.play(startPosition);
  channel.soundTransform=soundTransForm;
  channel.addEventListener("soundComplete",Next_Click);
  flushMediaPlayer();
 
  }
}
private function Sound_IOError_Handler(e:Event):void{
txtTip.text="Load Fail!";

}

private function Play_Click(_event:MouseEvent):void{
//1.播放;0.停止,2.暂停
if(play_tag!=1){

       playMusic();
}
}
private function Pause_Click(_event:MouseEvent):void{

if(channel!=null)
   {channel.stop();
    if(play_tag!=0)
       startPosition=channel.position;
}
else startPosition=0;
play_tag=2;

}
private function Stop_Click(_event:MouseEvent):void{
play_tag=0;
if(channel!=null)
channel.stop();
startPosition=0;

}
private function Close_Click(_event:MouseEvent):void{
Stop_Click(_event);
this.parent.removeChild(this);

}
private function Prev_Click(_event:MouseEvent):void{
currentIndex--;
if(currentIndex<0)
   currentIndex=0;
startPosition=0;
playMusic();

}
private function Next_Click(_event:Event):void{
currentIndex++;
if(musicList!=null&&currentIndex>musicList.length-1)
   currentIndex=0;
startPosition=0;
playMusic();
}

//处理静音
private function Volumn_Click(_event:MouseEvent):void{
if(soundAble)
   {
    btnJinYin.visible=true;
        soundTransForm.volume=0;
if(channel!=null)
              channel.soundTransform=soundTransForm;
soundAble=false;
   }
else {
btnJinYin.visible=false;
    soundAble=true;
}

}
       //时间函数相关
       //秒转换成时间MM:ss格式
private function formateTime(_seconds:int):String
{
var _result:String="";
var _mins:int=int(_seconds/60);
         var _secs:int=int(_seconds%60);
if(_mins<10)
            _result+="0"+_mins;
else _result+=_mins;
         if(_secs<10)
            _result+=":0"+_secs;
else _result+=":"+_secs;
         return _result;

    }

private function onEnterFramed(_event:Event):void{

if(sound!=null){
var loaded:int=sound.bytesLoaded;
var total:int=sound.bytesTotal;
if(soundAble){
soundTransForm.volume=(slVolumn.Volumn_Silder.x+2)/50;
channel.soundTransform=soundTransForm;
}
if(total>0){
var percentBuffered:Number=loaded/total;
txtTip.text="loaded:"+int(percentBuffered*100)+"%";
progressBar.AllData.width= percentBuffered*progressBarWidth;
if(play_tag==1){

var position:int=channel.position;
soundLength=int(sound.length/percentBuffered);
var percentPlayed:Number=position/soundLength;

progressBar.PlayedPosition_Line.width=(progressBarWidth-15)*percentPlayed;
if(!dragProgressSlider)
  progressBar.PlayedPosition.x=percentPlayed*(progressBarWidth-15);
startPosition=position/1000;
// setLrcValue();
txtTimeTip.text=formateTime(startPosition)+" / "+formateTime(soundLength/1000);
}
}
}
}

}
        
}