ActionScript 3.0 按钮控制音乐播放、暂停、停止、循环

ActionScript 3.0 按钮控制音乐播放、暂停、停止、循环

1 按钮

这里用3个Button组成一个MovieClip
MoiveClip的名称为:mcMusic
停止Button的名称为:btnStop
播放Button的名称为:btnPlay
暂停Button的名称为:btnPause

2 播放

从_pos位置开始播放。
注意:play与addEventListener不能互换位置。

private function _play(evt:MouseEvent):void {
    if (_isPause == true) {
        _soundChannel = _music.play(_pos);              
        _soundChannel.addEventListener(Event.SOUND_COMPLETE, _audioComplete);
        _isPause = false;
    }
}

3 暂停

注意:保存播放位置的代码与stop的代码不能互换位置。

private function _pause(evt:MouseEvent):void {
    if (_isPause == false) {
        _pos = _soundChannel.position;
        _soundChannel.stop();
        _isPause = true;
    }
}

4 停止

private function _stop(evt:MouseEvent):void {
    _soundChannel.stop();
    _pos = 0;
    _isPause = true;
}

5 循环

本来Sound的play方法中有一个loops参数用来设置要循环多少次,但是设为0和1的时候都是播放一次,并不能通过这个参数来设置无限循环。这里可以将循环次数设得很大,效果近似于无限循环,不过我还是不喜欢这样做。我的做法是,监听音乐的结束,结束时再播放。

private function _audioComplete(evt:Event): void {
    if (_isPause == false) {
        _soundChannel = _music.play();
        _soundChannel.addEventListener(Event.SOUND_COMPLETE, _audioComplete);
    }
}

6 完整文档类

package  {

    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    import flash.media.SoundChannel;
    import flash.events.Event;

    public class JMusic extends MovieClip {

        var _music:JCMusic = new JCMusic();
        var _soundChannel:SoundChannel = new SoundChannel();
        var _pos:Number = 0;
        var _isPause = false;

        public function JMusic() {
            mcMusic.btnMusicPlay.addEventListener(MouseEvent.CLICK, _play);
            mcMusic.btnMusicPause.addEventListener(MouseEvent.CLICK, _pause);
            mcMusic.btnMusicStop.addEventListener(MouseEvent.CLICK, _stop);

            _soundChannel = _music.play();
            _soundChannel.addEventListener(Event.SOUND_COMPLETE, _audioComplete);
        }

        private function _play(evt:MouseEvent):void {
            if (_isPause == true) {
                _soundChannel = _music.play(_pos);              
                _soundChannel.addEventListener(Event.SOUND_COMPLETE, _audioComplete);
                _isPause = false;
            }
        }

        private function _pause(evt:MouseEvent):void {
            if (_isPause == false) {
                _pos = _soundChannel.position;
                _soundChannel.stop();
                _isPause = true;
            }
        }

        private function _stop(evt:MouseEvent):void {
            _soundChannel.stop();
            _pos = 0;
            _isPause = true;
        }

        private function _audioComplete(evt:Event): void {
            if (_isPause == false) {
                _soundChannel = _music.play();
                _soundChannel.addEventListener(Event.SOUND_COMPLETE, _audioComplete);
            }
        }
    }
}

你可能感兴趣的:(actionscript,3.0)