13.3. Playing and Stopping a Sound

Problem

You want to play a sound or stop one from playing.

Solution

Use the start( ) and stop( ) methods of the Sound object that controls the sound.

Discussion

Sounds added to timelines at authoring time begin playback as soon as the playhead enters the frame containing the sound. In contrast, sounds that are added programmatically (see Recipe 13.2 and Recipe 15.5) do not begin playing until they are started with the Sound.start( ) method:

mySound_sound.start(  );

You can also specify the number of seconds into the audio track at which to begin playback by passing the start( ) method an optional offset parameter. For example, if you pass the start( ) method a value of 6, the audio will begin playing six seconds into the sound clip:

mySound_sound.start(6);

Unless directed otherwise, a sound plays once (until it reaches its end). You can stop a sound prematurely with the stop( ) method:

mySound_sound.stop(  );

You can also stop all sounds in a movie using the stopAllSounds( ) global function:

stopAllSounds(  );

When you stop a sound and then restart it, Flash automatically restarts the sound at the beginning.

See Also

To pause and resume sounds, see Recipe 13.7. See Recipe 13.6 for setting in and out points.

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.