AS3.0实现音乐的播放和停止

来源:互联网 发布:五粮春45度淘宝才70元 编辑:程序博客网 时间:2024/05/21 21:42

一.新建一个flash文档,在组件库中突出两个Button,实例名分别命名为:playBtn,stopBtn

二.建一个文件夹,music文件,有首歌:

春暖花开.mp3

二.as代码:

package ch14_1{import fl.managers.*;import flash.display.MovieClip;import flash.events.Event;import flash.events.MouseEvent;import flash.media.Sound;import flash.media.SoundChannel;import flash.net.URLRequest;import flash.text.TextFormat;public class MusicText2 extends MovieClip{var isPlaying:Boolean = false;var currntPosition:uint =0;var sound:Sound = new Sound();var channel:SoundChannel;public function MusicText2(){var f:TextFormat = new TextFormat();f.size =18;StyleManager.setStyle("textFormat",f);playBtn.label ="播放";stopBtn.label ="停止";stopBtn.enabled = false;sound.load( new URLRequest("music/春暖花开.mp3"));sound.addEventListener(Event.COMPLETE,loadComplete);}private function loadComplete(e:Event):void{stage.addEventListener(MouseEvent.CLICK,onClik);}private function onClik(e:MouseEvent):void{if(e.target ==playBtn){if(!isPlaying) {channel = sound.play(currntPosition);playBtn .label="暂停";stopBtn.enabled = true;}else{currntPosition = channel.position;channel.stop();playBtn.label ="播放";}isPlaying =! isPlaying;}else if(e.target ==stopBtn){channel.stop();currntPosition =0;isPlaying =false;}}}}