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);
}
}
}
}