15.10.暂停和重新播放声音

问题
我想暂停一下过一会儿再继续播放音乐
解决办法
利用SoundChannel的position属性即可做到
讨论
在第15.2章,我们讲过调用Sound对象的close( )方法可以停止播放,但是这样也停止了声音流,要想重新播放,必须再次调用load( )方法。

还好,SoundChannel类提供了一个stop( )方法,它可以让音乐暂停而不影响声音流中断,要想重新播放,调用play( )方法即可。

你会发现,当再次调用play( )方法时,音乐会从头开始播放而不是从暂停的地方开始,这个时候就要用到SoundChannel类的position属性了,把它作为play()方法的第一个参数,看下面的代码演示:
+展开
-ActionScript
package {
import flash.display.Sprite;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;
import flash.events.Event;
import flash.display.Sprite;
import flash.events.MouseEvent;
public class PlayPause extends Sprite {
private var _sound:Sound;
private var _channel:SoundChannel;
private var _playPauseButton:Sprite;
private var _playing:Boolean = false;
private var _position:int;
public function PlayPause( ) {
// Create sound and start it
_sound = new Sound(new URLRequest("song.mp3"));
_channel = _sound.play( );
_playing = true;
// A sprite to use as a Play/Pause button
_playPauseButton = new Sprite( );
addChild(_playPauseButton);
_playPauseButton.x = 10;
_playPauseButton.y = 20;
_playPauseButton.graphics.beginFill(0xcccccc);
_playPauseButton.graphics.drawRect(0, 0, 20, 20);
_playPauseButton.addEventListener(MouseEvent.MOUSE_UP,
onPlayPause);
}
public function onPlayPause(event:MouseEvent):void {
// If playing, stop. Take note of position
if(_playing) {
_position = _channel.position;
_channel.stop( );
}
else {
// If not playing, re-start it at
// last known position
_channel = _sound.play(_position);
}
_playing = !_playing;
}
}
}

上面的代码创建了一个按钮,当点击按钮时,如果正在播放,则暂停并记录位置,再次点击按钮时,继续从纪录的位置播放。

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


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