Pausing and Restarting a Sound : Sound « Development « Flash / Flex / ActionScript






Pausing and Restarting a Sound

 
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(  ) {
            _sound = new Sound(new URLRequest("song.mp3"));
            _channel = _sound.play(  );
            _playing = true;

            _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) {
                   _position = _channel.position;
                   _channel.stop(  );
            }
            else {
                // If not playing, re-start it at
                // last known position
                _channel = _sound.play(_position);
            }
               _playing = !_playing;
        }
    }
}

        








Related examples in the same category

1.Offsetting the Start of a Sound
2.Getting the Size of a Sound File
3.Reading the Sound Spectrum
4.Applying Sound Transformations
5.Buffering a Streaming Sound
6.Controlling Playback of a Sound
7.How Sound Works in AS3: assume that there is an MP3 file with the name sound.mp3 stored in the same folder as the SWF file.