In a previous tutorial, I demonstrated a simple solution to loading an external sound file. In that example, the mp3 file that had been loaded begins to play automatically. While this might be fine in some cases, you probably would want more control over the sound being imported.
For example, being able to stop or pause then play again might be a good place to start. In this tutorial, I will be demonstrating how to play, stop, and pause sounds using AS3 once you have the sound loaded into Flash.
Playing a sound
Playing a sound using AS3 is a simple as calling the play() method of the defined sound object. Previously in AS2, you would have called the start() method so not much different in this area.
Stopping a sound
Stopping a sound using AS3 is accomplished by calling the stop() method of the defined sound object. This is exactly the same way you would be able to handle it using AS2.
Pausing a sound
This is where pausing a sound using AS3 is quite different from using AS2. As it stands now, there is no method to automatically pause a sound using AS3. Instead, you must populate an optional parameter of the play() method.
It allows you to play the sound using an offset value that is passed in from a stored variable. Below is an example of accomplishing this.
//Stores the position of the "playback head" var pausePosition:Number = sndChannel.position; sndChannel.stop(); //When ready to resume playback, call this line sndChannel = soundClip.play(pausePosition);
Putting it all together
Now it is time to integrate all three. I have provided an example that puts all three of these control functionalities into good use. The example is sessentially a simple music player with toggle functionality.
Subscribe to the RSS Feed to stay updated on future tutorials on using sound in AS3.
I hope this helps in your migration over into AS3. If there is something in particular you want to add or see with the Moving From AS2 to AS3 series, feel free to contact me via the contact page.