Flash学习As3音乐播放器教程
- 格式:docx
- 大小:25.97 KB
- 文档页数:11
Flash MP3 Music Player Tutorial – AS3原文地址:/view/tutorial/How-To-Create-Flas h-Music-Player-With-AS3/57051标签:as3, 组件, flash 播放器r , mp3 播放器, music 播放器发布于:Flash Tutorials在本教程中, 你将学习如何使用AS3和XML 制作一个音乐播放器 。
在文中,我将一步步的讲解元件的设计和代码的编写。
你也将学到如何为按钮添加效果,如何制作右键选单和使用XML 文件轻松方便的修改、更新你的音乐信息。
用文中的方法你只需一会儿的功夫就能做一个音乐播放器。
所以,Come on! Let's enjoyit~~具体效果如下:即将开始我们将用到Tween 效果. 点击这里下载 TweenMax.我将把AS 的解释放在代码区。
你只需要“小心”跟着就可以了。
我确信即使你还不懂AS ,你也能做出这个播放器。
让我们来开始制作它吧~~步骤 1 – 准备文件夹我们必须建一个主文件夹来存放所有的子文件夹和文件。
建一个新文件夹并作如下操作:1.将TweenMax的"com"文件夹放到这主文件夹中。
2.建一个名为“musics”的新文件夹. 把你的歌放到里面。
3.建一个AS3 的Flash项目和一个XML项目(用DW或者记事本)4.保存它们。
你需要的文件夹如下:步骤 2 –搭建舞台打开你刚才保存的Flash项目。
这里每个属性都是可以修改的。
我用的是样本值。
舞台大小为300×200。
背景颜色(# 191611)。
步骤 3 –制作播放器的背景我们用一个长方形(Buttonrectangle)和一个正方形(Coversquare)作为背景图片。
线条颜色(#3E362D),填充颜色(#2F2922)。
布置如下。
步骤 4 –插入皮肤图片导入(Ctrl + R) 你的图片到舞台并把它嵌入Coversquare 中。
flash如何制作音乐播放器一(22)
1.如图所示,我们新建一个flash的文档,之后我们点击箭头所指的的“插入”
选项,在弹出的下拉列表菜单中,我们点击箭头所指的“新建元件”这一项。
2.如图所示,在弹出的对话框中,我们输入这个元件的名称,之后选择元件
的类型,然后点击“确定”按钮,就可以新建一个按钮类型的元件了。
3.如图所示,我们在箭头所指的“点击”这一帧处鼠标右击,在弹出的上拉列
表菜单中,我们点击箭头所指的“插入关键帧”选项,就可以在此插入关键帧了。
4.如图所示,我们接下来点击箭头所指的“文件”选项,在弹出的下拉列表菜
单中,我们点击“导入(I)”选项,之后依次点击“导入到库(L)”选项。
5.如图所示,在弹出的文件对话框中,我们选择一个mp3的音乐文件(这
里是为了演示,所以选择哪一首个都是可以的。
),之后点击箭所指的“打开”按钮,就可以将这首歌导入到库中了。
1. 6
6.如图所示,我们将这首刚导入到库中的歌曲,拖拉到“点击”这一帧里面,
就会为了,在鼠标点击时,对这首歌进行操作。
2.7
7.如图所示,我们点击“点击”这一帧处,然后点击打开其属性面板,在面板
中我们点击箭头所指的黑三角,在弹出的下拉列表菜单中,我们点击箭头所指的的“开始”这一项,这表示在鼠标点击时,这首歌曲就可以播放。
3.8
8.如图所示,点击箭头所指的的“插入”选项,在弹出的下拉列表菜单中,我
们点击箭头所指的“新建元件”这一项。
4.9
9.如图所示,在弹出的对话框中,我们输入这个元件的名称,之后选择元件
的类型,然后点击“确定”按钮,就可以新建一个停止播放歌曲的元件了。
再学AS3(六):音乐播放器1--控制播放进度主要功能:点击进度条音乐从鼠标点击处开始播放。
制作过程:1、新建FLASH CS3文档,保存名为“音乐播放器进度控制”,保存在存有音乐的文件夹内。
设置文档大小:252×114像素,帧频:24fps。
2、第一层名为“播放器背景”,在该层画一个播放器背景。
3、新建图层,名为“播放进度框”,画一个无边框的圆角矩形,边角半径为8,宽202高6,填充颜色为#006600,使其垂直水平于舞台。
4、新建图层,名为“播放进度背景”,画一个无边框的圆角矩形,边角半径为8,宽200高4,从上到下填充#99CC00到#55802B渐变色,使其垂直水平于舞台。
5、新建图层,名为“播放进度条”,画一个无边框的圆角矩形,边角半径为0,宽202高6,从上到下填充#00CCFF到#0066FF渐变色,使其垂直水平于舞台,转换为名为“播放进度条”的影片剪辑。
在场景中的实例名为“bfjdt_mc”。
6、新建图层,名为“播放进度条遮罩”,把“播放进度背景”图层上帧复制并粘贴到“播放进度条遮罩”图层上,右键选择“遮罩层”。
7、新建图层,名为“进度控制”,画一个无边框的圆角矩形,边角半径为0,宽200高6,填充颜色任意,使其垂直水平于舞台,转换为名为“进度控制”的按钮元件,并将“弹起”帧上的图形拖到“点击”帧上。
在场景中的实例名为“jdcz_btn”。
8、新建图层,名为“AS”,在帧上写如下代码://申明变量var _sound:Sound=new Sound();var _channel:SoundChannel=new SoundChannel();var loaded:int;var total:int;var _length:int;var position:int;var percentBuffered:Number;var percentPlayed:Number;//载入MP3并播放var url:String="****.mp3";//你电脑上的MP3音乐文件名,把该文件与MP3音乐文件放在一个文件夹内。
as3一个完整的音乐播放类1.建立播放、停止、暂停类package {import flash.display.Sprite;import flash.media.Sound;import flash.media.SoundChannel;import .URLRequest;public class LoadSoundExample extends Sprite { private var _sound: Sound;private var _channel: SoundChannel;private var _position: int;private var _playing: Boolean = false;public function LoadSoundExample() {_sound = new Sound();_sound.load(new URLRequest("ppp1.mp3"));//_channel = _sound.play();}//播放public function aa(): void {// _sound.play()_channel = _sound.play()_playing = true;}//暂停public function bb(): void {_channel.stop()}//退出public function cc(): void {if (_playing) {_position = _channel.position;_channel.stop();} else {// 如果未播放,从记录处开始播放//_channel = _sound.play(_position); }_playing = !_playing;//_sound.play()}}}2、建立三个按钮p1,p2,p33、在FLA文件中import LoadSoundExampleimport flash.media.Soundimport flash.media.SoundChannel;import flash.events.Event;var kk: LoadSoundExample = new LoadSoundExample()var ll: Sound = new Sound()var sy: SoundChannel = new SoundChannel()kk.addEventListener(PLETE, onSoundLoaded);function onSoundLoaded(event: Event): void {}p1.addEventListener(MouseEvent.CLICK,fl_MouseClickHandler1);function fl_MouseClickHandler1(event: MouseEvent): void { trace("sadasdsadsad")kk.aa()}p2.addEventListener(MouseEvent.CLICK,fl_MouseClickHandler2);function fl_MouseClickHandler2(event: MouseEvent): void { trace("sadasdsadsad")kk.bb()}p3.addEventListener(MouseEvent.CLICK,fl_MouseClickHandler3);function fl_MouseClickHandler3(event: MouseEvent): void { trace("sadasdsadsad")() }。
基于Flash编写的WEB版音乐播放器代码一:package{import flash.media.Sound ;import flash.media.SoundChannel;import flash.media.SoundTransform ;import flash.media.SoundLoaderContext ;import .URLRequest ;import .URLStream ;import flash.events.MouseEvent ;import flash.events.IOErrorEvent;import flash.events.Event ;import flash.events.ProgressEvent ;public class Audio{/*歌曲播放头*/private var playHead:uint=0 ;/*播放状态,0:什么也没有,1:播放,2:暂停,3:停止*/private var playState:uint=0;/*声音状态,0:正常1:静音2:最大音·*/private var volState:uint=0;private var sound:Sound ;private var channel:SoundChannel ;private var transfor:SoundTransform ;private var uRequest:URLRequest ;private var loadContext:SoundLoaderContext ;public function Audio(){loadContext=new SoundLoaderContext(1000,false) ;//跨域策略处理}/******************next/pre/current***************************************/public function switchPath(path:String,vol:Number):void{transfor=new SoundTransform (vol,0);this.soundObject(path);}private function soundObject(path:String):void{try{if(this.channel){this.channel.stop();this.setPlayState(3);}if(this.sound.isBuffering){this.sound.close();this.setPlayState(3);}}catch(e){}finally{sound=new Sound() ;uRequest=new URLRequest(path) ;uRequest.method='POST';this.soundEvent();sound.load(uRequest,loadContext);}}/*******************************************************load**************** ******************************************/private function loadOpen(e:Event):void{//trace('Start Run');}private function loadProgress(e:ProgressEvent):void{Main.soundTotalBytes(r_soundTotalBytes());Main.soundLoadedBytes(r_soundLoadedBytes());}private function loadError(e:IOErrorEvent):void{Main.soundError();}private function loadComplete(e:Event):void{if(!this.soundBuffered()){Main.soundTotalTime(r_soundLength());this.event_playEvent();}}/*******************************************************XXXXXXXX******* ***************************************************/public function soundBuffered():Boolean//true在缓冲,false缓冲结束{return sound.isBuffering ;}/*******************************************************contro_*,pause/stop/pla y,forward/back/up/down*********************************************************/ public function contro_pauseEvent():void{this.event_pauseEvent();}public function contro_stopEvent():void{this.event_stopEvent();}public function contro_playEvent():void{this.event_playEvent();}public function contro_adjustPlayHead(position:Number):void{if(this.getPlayState()==1 || this.getPlayState()==2){try{this.channel.stop();this.channel=this.sound.play(position,0,this.transfor);this.soundPlayOver() ;}catch(e){}}}public function contro_adjustV olume(vol:Number):void{this.transfor.volume=vol;this.channel.soundTransform=this.transfor;}public function contro_playOver(e:Event):void{this.playHead=0;Main.sendSoundPlayState();}/*******************************************************event_************** ********************************************/private function event_pauseEvent():void{if(this.getPlayState()==1 || this.channel){this.playHead=this.channel.position;this.channel.stop();this.setPlayState(2);}}private function event_playEvent():void{if(this.getPlayState()==2){this.channel=this.sound.play(this.playHead,0,this.transfor);this.soundPlayOver() ;this.setPlayState(1);}if(this.getPlayState()==3 || this.getPlayState()==0){this.channel=this.sound.play(0,0,this.transfor);this.soundPlayOver() ;this.setPlayState(1);}}private function event_stopEvent():void{if(this.getPlayState()==2||this.getPlayState()==1){this.channel.stop();this.playHead=0;this.setPlayState(3);}}/*******************************************************infor_************** ********************************************/public function infor_soundLoadedBytes():uint{return this.sound.bytesLoaded ;}public function infor_soundTotalBytes():int{return this.sound.bytesTotal ;}public function infor_soundLength():Number{return this.sound.length ;}public function infor_currentPlayHead():Number{return this.channel.position ;}public function infor_soundUrl():String{return this.sound.url ;}/*----------------------------------------------------------播放状态和声音状态设置-----------------------------------------------------------------------------*/private function setPlayState(stateValue:uint):void{switch(stateValue){case 0: this.playState=0;break;case 1: this.playState=1 ;break;case 2: this.playState=2;break;case 3: this.playState=3;break;}}public function getPlayState():uint{return this.playState ;}private function setV olState(stateValue:uint):void{switch(stateValue){case 0: this.volState=0;break;case 1: this.volState=1 ;break;case 2: this.volState=2;break;}}public function getV olState():uint{return this.volState ;}private function soundPlayOver():void{this.channel.addEventListener(Event.SOUND_COMPLETE,this.contro_playOver);}private function soundEvent():void{this.sound.addEventListener(Event.OPEN ,loadOpen) ;this.sound.addEventListener(PLETE,loadComplete);this.sound.addEventListener(IOErrorEvent.IO_ERROR,loadError);this.sound.addEventListener(ProgressEvent.PROGRESS,loadProgress);}}}代码二:package{import flash.display.Sprite ;import flash.events.MouseEvent ;import flash.events.TimerEvent ;import flash.utils.Timer ;import flash.ui.ContextMenu ;import flash.ui.ContextMenuItem ;import flash.external.ExternalInterface ;import flash.system.Security;import Audio ;public class Main extends Sprite{private var audio:Audio ;private var path:String;private var vol:Number;public function Main(){if(ExternalInterface.available){flash.system.Security.exactSettings=true;flash.system.Security.allowDomain("*");try{var containerReady:Boolean=isContainerReady() ;if(containerReady){setupCallbacks();}else{var readyTimer:Timer=new Timer(10,0);readyTimer.addEventListener(TimerEvent.TIMER,timerHander);readyTimer.start();}}catch(e){}}/*this.audio=new Audio();this.songObject('zhou.mp3',1);*/this.copyright( ) ;}private function isContainerReady():Boolean{var readyResult:Boolean=ExternalInterface.call("isReady") ;//调用JS的isReadyreturn readyResult ;}private function timerHander(e:TimerEvent):void{var isReady:Boolean=isContainerReady();if(isReady){Timer(e.target).stop();setupCallbacks();}}//------------------------------------------------------------------------------------------让JS调用--------------------------------------------private function setupCallbacks():void{this.audio=new Audio();ExternalInterface.addCallback("onPause",onPause) ;ExternalInterface.addCallback("onRecover",onRecover) ;ExternalInterface.addCallback("onStop",onStop) ;ExternalInterface.addCallback("onV ol",onV ol) ;ExternalInterface.addCallback("onState",onState) ;ExternalInterface.addCallback("onHead",onHead) ;ExternalInterface.addCallback("onPosition",onPosition) ;ExternalInterface.addCallback("onBuffer",onBuffer) ;ExternalInterface.addCallback("songObject",songObject) ;}//--------------------------------------------------------------------对JS接口------------------------------------------------------------//上一首或下一首private function songObject(path:String,vol:Number):void{this.path=path;this.vol=vol;if(path==''){var _readyTimer:Timer=new Timer(10,0);_readyTimer.addEventListener(TimerEvent.TIMER,_timerHander);_readyTimer.start();}else{this.audio.switchPath(this.path,this.vol);txt.text=String('Run');}}private function _timerHander(e:TimerEvent):void{if(this.path!=''){Timer(e.target).stop();this.audio.switchPath(this.path,this.vol);txt.text=String('Run');}}//暂停播放private function onPause():void{this.audio.contro_pauseEvent();txt.text=String('Pause');}//恢复播放private function onRecover():void{this.audio.contro_playEvent();txt.text=String('Recover');}//停止播放private function onStop():void{this.audio.contro_stopEvent() ;txt.text=String('Stop');}//控制声音private function onV ol(volValue:Number):void{this.audio.contro_adjustV olume(volValue) ;}//用来快进或后退private function onHead(setPlayHead:Number):void{this.audio.contro_adjustPlayHead(setPlayHead);}//判断歌曲是播放还是暂停或停止private function onState():uint{return this.audio.getPlayState();//------------------------0/1/2/3 }//判断是否在缓冲private function onBuffer():Boolean{return this.audio.soundBuffered();}//当前歌曲播放头private function onPosition():Number{return r_currentPlayHead() ;}//---------------------------------------------------------------------------供Audio调用/-------------------------------------------------//向JS报告该歌曲一播放完public static function sendSoundPlayState():void{ExternalInterface.call("playOver","OVER");}//报告歌曲总时间public static function soundTotalTime(totalTimeValue:Number):void{ExternalInterface.call("totalTime",totalTimeValue);}//报告歌曲总字节数public static function soundTotalBytes(totalBytesValue:uint):void{ExternalInterface.call("totalBytes",totalBytesValue);}//报告歌曲当前已经加载字节数public static function soundLoadedBytes(loadedBytesValue:uint):void{ExternalInterface.call("loadedBytes",loadedBytesValue);}public static function soundError():void{ExternalInterface.call("loadedError","the path can be error");}//---------------------------------------------------------------------------版权-----------------------------------------------------------------------------private function copyright():void{var menu:ContextMenu=new ContextMenu( ) ;var menuItem01:ContextMenuItem=new ContextMenuItem('Yue 1.0.2') ;var menuItem02:ContextMenuItem=new ContextMenuItem('© 2013 quanyao AllReserved') ;menu.customItems.push(menuItem01, menuItem02);contextMenu=menu ;}}}WEB的JS部分:// JavaScript Document/*******************************以下是类*******************************************************/var jsReady =false;var swfpath ='player.swf';/***********初始化都为零,记录歌曲信息***************************/var infor={length:0 ,tbytes:0 ,lbytes:0 ,vol :parseFloat(0.5)//默认音量0.5,[0,1]}function Init(){jsReady=true;}/******************JS*********************************/function songObject(path){thisMovie('player').songObject(path,infor.vol);}function onRecover(){thisMovie('player').onRecover();}function onPause()thisMovie('player').onPause();}function onStop(){thisMovie('player').onStop();}function onVol(vol)//调整声音{thisMovie('player').onV ol(vol);}function onHead(value)//调整播放进度{thisMovie('player').onHead(value);}function onState()//获取播放状态,0/1/2/3{return thisMovie('player').onState();}function onPosition()//获取播放头{return thisMovie('player').onPosition();}function onBuffer()//判断是否在缓冲,true/false {return thisMovie('player').onBuffer();}/***************AS*******************/ function isReady(){return jsReady;}function playOver(state){alert(state);}function totalTime(value){infor.length=value ;function totalBytes(value){infor.tbytes=value;}function loadedBytes(value){infor.lbytes=value;}function loadedError(val){alert(val);}function thisMovie(movieName){if(navigator.appName.indexOf("Microsoft") != -1){return window[movieName];}else{return document[movieName];}}function tag(){$('body').append("<div><embed src='"+swfpath+"' name='player' quality='high' width='200' height='40' align='middle' play='true' loop='false' quality='high' allowScriptAccess='sameDomain' type='application/x-shockwave-flash' pluginspage='http =///go/getflashplayer' swfversion='6.0.65.0' expressinstall='Scripts/expressInstall.swf'></embed></div>");}jQuery(function(){tag();jsReady=true;});/****************转换时间格式**************************************/function timeFormat(timeValue){var m,s,ms;m=parseInt(timeValue/1000/60);s=parseInt(timeValue/1000-m*60);ms=parseInt(timeValue%1000/10);m=m>9?m:('0'+m);s=s>9?s:('0'+s);ms=ms>9?ms:('0'+ms);return m+':'+s;}/**************************解析歌词*************************************/var lyric={readLyric:function(serverPath,lyricPath){var lyricObject,proxy=this;$.post(serverPath,{path:lyricPath},function(message){if(message!=''){lyricObject=this.analysisLyric(message);//解析歌词this.showLyric(lyricObject);//显示歌词}else{proxy.noLyric();//????????????/}});},analysisLyric:function(lyric){var title,artist,album,by,arr=new Array(),lyricArr=new Array(),timeArr=new Array(),lyricObject=new Array();lyricObject[0]=timeArr,lyricObject[1]=lyricArr;//用lyricObject来封装歌词和时间arr=lyric.split('\n');for(var i=0;i<arr.length;i++){//substring(start,end)方法返回字符串包括start位置但不包括end,substr(start,[length])if(arr[i].substr(arr[i].indexOf(']')+1)!="")//过溜掉歌词为空的即其时间轴{lyricArr[i]=arr[i].substr(arr[i].indexOf(']')+1);timeArr[i]=arr[i].substring(arr[i].indexOf('[')+1,arr[i].indexOf('.'));}else{}}return lyricObject;},showLyric:function(lyric){isDisplay:false//判断歌词是否准备好},moveLyric:function(){},noLyric:function(tagName){$(tagName).append("<p>--没有找到歌词--</p>");}}JS部分添加了歌词解析部分下载地址/download/。
Flash as3实例教程:AS3.0构建简单的声音可视化程序本例为Flash AS3.0实例教程,在教程中我们将学习运用puteSpectrum()方法来构建简单的声音可视化程序(即波形图),希望能给朋友们带来帮助~~AS3.0构建简单的声音可视化程序(波型图)使用puteSpectrum() 方法来显示声音波形图import flash.display.Graphics;import flash.events.Event;import flash.media.Sound;import flash.media.SoundChannel;import flash.media.SoundMixer;import .URLRequest;constPLOT_HEIGHT:int = 200;constCHANNEL_LENGTH:int = 256;varsnd:Sound = new Sound();varreq:URLRequest = new URLRequest("月亮之上.mp3");//配置声音源文件地址(此为本地,可配置远程)snd.load(req);varchannel:SoundChannel;channel = snd.play();addEventListener(Event.ENTER_FRAME, onEnterFrame);snd.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);varbytes:ByteArray = new ByteArray();function onEnterFrame(event:Event):void{puteSpectrum(bytes, false, 0);var g:Graphics = this.graphics;g.clear();g.lineStyle(0, 0x6600CC);g.beginFill(0x6600CC);g.moveTo(0, PLOT_HEIGHT);var n:Number = 0;// left channelfor (var i:int = 0; i< CHANNEL_LENGTH; i++){n = (bytes.readFloat() * PLOT_HEIGHT);g.lineTo(i * 2, PLOT_HEIGHT - n);}g.lineTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);g.endFill();// right channelg.lineStyle(0, 0xCC0066);g.beginFill(0xCC0066, 0.5);g.moveTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);for (i = CHANNEL_LENGTH; i> 0; i--){n = (bytes.readFloat() * PLOT_HEIGHT);g.lineTo(i * 2, PLOT_HEIGHT - n);}g.lineTo(0, PLOT_HEIGHT);g.endFill();}function onPlaybackComplete(event:Event){removeEventListener(Event.ENTER_FRAME, onEnterFrame);}先加载并播放一个声音文件,然后在播放声音的同时侦听将触发onEnterFrame() 方法的Event.ENTER_FRAME事件。
as3.0的sound类常用技巧(一)、如何把声音文件作为一个变量加载到swf文件中。
创建一个Sound对象,然后加载具体的声音文件到里面创建一个Sound对象和创建其他对象一样简单,首先我们必须保证相关的类已经被导入。
import flash.media.Sound;然后,直接创建声音对象的一个实例就可以了:_sound = new Sound();当然,现在你还需要为声音对象一个具体的声音,比如一首歌,结下来,我们在例子中提到的所有音乐都用song.mp3来代替,把它保存在.swf文件同一个目录下。
要想加载声音文件到刚刚建立的Sound对象中,还要先创建一个URLRequest对象(在此我们还必须导入相关的类 import .URLRequest,通过字符串表示mp3文件的路径:soundFile = new URLRequest(“song.mp3″);接下来,我们就可以用下面这个语句来实现加载声音文件了:_sound.load(soundFile);package {import flash.display.Sprite;import flash.media.Sound;import .URLRequest;public class LoadSoundExample extends Sprite {private var _sound:Sound;public function LoadSoundExample( ) {_sound = new Sound( );_sound.load(new URLRequest(“song.mp3″));}}}上面的类LoadSoundExample就有了一个_sound属性,你可以在任何时候用它来播放音乐。
说明一下:此时的声音还并没有开始播放。
现在我们只是设置了有一个声音(sound)和它具体是什么样的声音(song.mp3)。
(二)如何播放一个或者停止一个音乐的播放用sound对象的play()方法开始播放声音,用sound对象的close()方法停止音乐的播放。
Flash学习As3音乐播放器教程那么开始吧!大家先下载一下源文件。
对着源文件的结构看教程。
我将整个播放器做到一个元件中(Control_panel),再给它绑定一个类(sound_lib.Control_panel),所有的代码就写在这个类里面了。
这样做的好处是:日后要用到它时,直接把Control_panel元件拖到你要用的地方就Ok了!接下来就是code了:要做音乐播放器,最重要的两个类当然就是Sound和SoundChannel。
先试一下,怎样让一首mp3播放起来:1. //建立一个Sound类2. sound=new Sound()3. //加载mp3文件4. sound.load(new URLRequest(“你的mp3路径”))5. //播放6. sound.play()Ok了!完整代码:1. package sound_lib{2. import flash.display.*3. import flash.media.Sound4. import flash.media.SoundChannel5. import .URLRequest6. public class Control_panel extends MovieClip{7. private varsound:Sound8. private constsound_url:String="sound_data/m01.mp3"9. public function Control_panel(){10. init()11. }12. private function init(){13. sound_init()14. }15. function sound_init(){16. sound=new Sound()17. sound.load(new URLRequest(sound_url))18. sound.play()19. }20. }21. }22.Ctrl+Enter一下。
是不是听到音乐了?啊?没听到?看看sound_data目录下是否放了mp3文件没?如果一切正常的话,你现在应该在享受你的音乐了。
呵呵。
不过别忘了大多数播放器是要用在web上的。
有时候声音播放的速度可能比下载的速度还要快,这种情况下声音播放就会暂停等待数据下载,为了更好的处理这个环节,我们可以设置一个数据缓冲区,当声音数据下载到一定数量时再进行播放,这样的话即使下载速度偶尔变慢也不会影响正常播放。
默认下Sound对象只创建1秒钟的缓冲,也就是说要想立即播放也需要等待1秒钟的缓冲,缓冲区的数据播放完后要想再次播放还要至少等1秒钟缓冲时间。
显然如果网速较慢的话且缓冲为1秒时,在这种情况下音乐的播放将会给人很”卡”的感觉。
所以我们必需手动设置一下缓冲:设置缓冲需要用到SoundLoaderContext类:建立一个SoundLoaderContext对象,然后设置它的bufferTime属性就行了。
最后将SoundLoaderContext对象传给sound对象的load()方法的参数就行了。
1. //建立一个SoundLoaderContext类,设置bufferTime为5秒2. varbuffer:SoundLoaderContext=new SoundLoaderContext(5000)3. sound=new Sound()4. sound.load(new URLRequest(sound_url),buffer)5. sound.play()声音的暂停与回放这样,即使放到web上也不成问题了。
不过现在只是能正常播放了,我们还得控制它才行嘛!最常见的控制就是暂停与回放了。
声音的暂停与回放不像视频流那样,可以直接pause 和resume来操作。
看看Soun类,大家可能会调用Sound对象的close( )方法可以停止播放,但是这样也停止了声音流,要想重新播放,必须再次调用load( )方法。
这显然不是我们想要的。
这里我们终于要用到上面所提到的SoundChannel了,其实对音频的绝大多数操作都是SoundChannel类来完成的。
SoundChannel的stop()方法可以让音乐暂停而不影响声音流的中断。
于是我们可以用SoundChannel对象的stop()方法与Sound对象的play()方法来暂停与回流音频流。
但是,当再次调用play( )方法时,音乐会从头开始播放而不是从暂停的地方开始,这个时候就要用到SoundChannel类的position属性了:position属性是用来记录音乐播放头的。
我们可以在暂停时,记录下position的值,然后再次调play()时,将它传给play()方法的参数。
这样就达到了最终目:1. sound_channel.stop()2. //记录position属性3. position=sound_channel.position4. sound_channel=sound.play(position)完整代码:1. package sound_lib{2. import flash.display.*3. import flash.media.Sound4. import flash.media.SoundChannel5. import flash.media.SoundLoaderContext6. import flash.events.*7. import .URLRequest8. public class Control_panel extends MovieClip{9. private varsound:Sound10. private constsound_url:String="sound_data/m01.mp3"11. private varsound_channel:SoundChannel12. private varposition:int13. private varis_play:Boolean14. public function Control_panel(){15. addEventListener(Event.ADDED_TO_STAGE,add_to_stage)16. }17. private function add_to_stage(_evt:Event):void{18. init()19. }20. private function init(){21. sound_init()22. control_init()23. }24. //==================sound part====================//25. function sound_init(){26. varbuffer:SoundLoaderContext=new SoundLoaderContext(5000)27. sound=new Sound()28. sound.load(new URLRequest(sound_url),buffer)29. sound_channel=sound.play()30. is_play=true31. play_mc.visible=false32. }33. //===================control part=================//34. function control_init(){35. pause_mc._btn.addEventListener(MouseEvent.CLICK,is_play_Handler)36. play_mc._btn.addEventListener(MouseEvent.CLICK,is_play_Handler)37. }38. private function is_play_Handler(_evt:MouseEvent):void{39. if(is_play){40. is_play=false41. position=sound_channel.position42. sound_channel.stop()43. play_mc.visible=true44. pause_mc.visible=false45. }else{46. is_play=true47. sound_channel=sound.play(position)48. play_mc.visible=false49. pause_mc.visible=true50. }51. }52. }53. }Ctrl+Enter一下。
Ok了吧?跟踪声音的加载进度与播放进度要得到声音的加载进度是很简单的,Sound类本身有bytesLoaded属性与bytesTotal属性。
只要在progress事件中监测到这个属性值就Ok了具体操作如下:1. private function sound_loading_Handler(_evt:ProgressEvent):void{2. varloaded_per=Math.ceil(100*_evt.bytesLoaded/_evt.bytesTotal)/1003. scroll_bar.loading_bar.scaleX=loaded_per4. }5. // loaded_per就是加载进度的百分比了,简单吧!不过用户肯定不满足于只看到加载进度,他们更希望能看到声音的播放进度并能控制播放进度。
要得到播进度,必须知道两个值:音乐的长度和当前的播放位置。
这两个属性分别在两不同的类里。
长度属性在sound类里,播放位置在SoundChannel类里,这两个值相除就是播放进度百分比。
呵呵,就这么简单!不过好像高兴得有点早了:sound类的length属性是不确定的,直到声音被下载完才确定,也就说它只表示已经被下载的那部分数据的长度,举个例子说,如果一个10分钟的音乐已下载了10%,那么length报告歌曲长度为1分钟(length 和position的单位都是毫秒)。
不过从我上面的例子不难看出,只要长度除以加载进度百分比即可算出实际长度即sound_length/loaded_per。
嗯原理搞清楚了就来试试吧:1. var loaded=sound.bytesLoaded2. var total=sound.bytesTotal3. sound_length=sound.length4. if(total>0){5. varloaded_per=loaded/total6. scroll_bar.loading_bar.scaleX=loaded_per7. sound_length=length/loaded_per8. position=sound_channel.position9. varplayed_per=position/sound_length10. }好了。