ProblemYou want to pause a sound and restart it later from where it stopped playing. SolutionTake note of the position property of the sound's SoundChannel. When you restart the sound, use that value as an offset. DiscussionAs noted in Recipe 15.2, you can call the close( ) method of a Sound object to make it stop playing. However, this also stops the sound from streaming, so to replay it, you'll need to re-call the load( ) method. Fortunately, the SoundChannel class offers a stop( ) method, which causes the sound to stop playing without affecting the loading. To restart the sound, just call the play( ) method again. You should note, however, that the play( ) method causes the sound to start from the beginning. This is the expected behavior for a "stop" button, as seen on many media players. Creating a "pause" button takes a bit more work. The strategy is to set up a handler method that's called when a pause button is pressed. In this function, read and store the current position of the SoundChannel, which gives you the time in milliseconds from the sound's beginning. Store this in a class variable so it can be accessed later. At this point, the pause button becomes a play button. When pressed again, call the play( ) method of the Sound object, passing in the saved position. This causes the sound to play from that point, which is the exact point at which it stopped. The following example demonstrates this strategy: 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; } } } The code creates a sprite to serve as a button. In the mouse up handler, the sound is stopped if it is playing, and its position is noted. The next time the button is pressed, the sound starts playing at the position where it left off. See AlsoRecipe 15.2 |