Sound Basics In Actionscript 3

June 17th, 2009

Below is a bare bones example of how to play a sound using AS3.

//////playing an external sound file
var sound:Sound = new Sound(new URLRequest("test.mp3"));
sound.play();

//////playing a sound file from the library
var sound:YourLibrarySound = new YourLibrarySound();
sound.play();





Below I add a little bit of functionality using the soundchannel class to pause and play the sound. The trick is to save the position property of the soundchannel instance when you stop the soundchannel. This value is simply where the playhead is in milliseconds. You can then resume playing the sound where it left off by adding this value as the first parameter of the of the play method. FYI, the second value of the play method is how many times the sound will loop.

//////playing an external sound file
var sound:Sound = new Sound(new URLRequest("test.mp3"));
var channel:SoundChannel = sound.play();

var isPlaying:Boolean = true;
var pausePosition:Number;

stage.addEventListener(MouseEvent.CLICK, clickHandler);

function clickHandler(e:MouseEvent):void
{
	if(isPlaying)
	{
		pausePosition = channel.position;
		channel.stop();
		isPlaying = false;
	}else{
    	channel = sound.play(pausePosition);
        isPlaying = true;
	}
}

Flash / Actionscript

  1.  
    No comments yet.
     
Post a Comment
  1. No trackbacks yet.
You must be logged in to post a comment.