15.8.判定音乐是否播放完毕

问题
开始播放后,我想知道什么时候播放完毕
解决办法
监听soundComplete事件。
讨论
很多情况下我们需要知道什么时候音乐会播放完毕,例如,音乐播放器的播放列表,需要判定是否播放完毕以便播放下一首音乐。

这一节我们将介绍flash.media包中的SoundChannel类。当我们调用Sound对象的play( )方法时,它会返回一个SoundChannel对象,因此每一首正在播放的音乐都会产生一个SoundChannel对象,这些声道合并并且最终输出。
当声音播放完毕时, 对应的SoundChannel 对象会发出soundComplete 事件, 就是flash.events.Event.SOUND_COMPLETE。
下面的例子建立一个简单的播放列表:
+展开
-ActionScript
package {
import flash.display.Sprite;
import flash.media.Sound;
import flash.net.URLRequest;
import flash.events.Event;
import flash.media.SoundChannel;
public class PlayList extends Sprite {
private var _sound:Sound;
private var _channel:SoundChannel;
private var _playList:Array; // the list of songs
private var _index:int = 0; // the current song
public function PlayList( ) {
// 创建列表,开始播放
_playList = ["song1.mp3",
"song2.mp3",
"song3.mp3"];
playNextSong( );
}
private function playNextSong( ):void
{
// If there are still songs in the playlist
if(_index < _playList.length) {
// Create a new Sound object, load and play it
// _playList[_index] contains the name and path of
// the next song
_sound = new Sound( );
_sound.load(new URLRequest(_playList[_index]));
_channel = _sound.play( );
// Add the listener to the channel
_channel.addEventListener(Event.SOUND_COMPLETE,
onComplete);
// Increase the counter
_index++;
}
}
public function onComplete(event:Event):void
{
playNextSong( );
}
}
}

这里变量_index 起始值为0,则_playList[index]正好等于"song.mp3",这将是第一首播放的歌曲,接着_index 自增,当soundComplete 事件触发时将会播放下一首歌,直到_index 大于_playList的长度。

加支付宝好友偷能量挖...


评论(0)网络
阅读(124)喜欢(0)flash/flex/fcs/AIR