Recipe 15.4. Offsetting the Start of a Sound


Problem

You want a sound to start playing, not from the start of the sound, but at a position some ways into it.

Solution

Pass a start time to the play( ) method.

Discussion

There may be instances when you want to start playing a sound file, but not from the very beginning of the sound. In other words, you want to cut off some amount from the start of the sound and play it from that offset point. The Sound object gives you very precise control so you can pinpoint the exact place where a sound will start playing, right down to the millisecond.

If you call a Sound object's play( ) method without any parameters, it starts playing from the very beginning. But you can pass it an optional parameter that is the number of milliseconds into the sound at which you want it to start. For example, the following causes the sound to start playing at exactly 5.5 seconds after its beginning point:

_sound.play(5500);

This particularly comes in handy when you have a sound file that has some introductory material at the beginning that you want to skip over. If you can't edit the sound file to cut that part out, all you need to do is set the start time and skip over the initial portion.

Another example would be to create a system of cue points in the sound. Say you had a recording of a speech and you wanted to allow users to listen to any of several portions of that speech. Taking note of the points at which each portion begins, you can set these up as cue point values in an array. Now, by specifying which cue point to start playing the sound from, you can get the start time from the array and pass that to the play( ) method. The following class demonstrates a simple example of this:

package {     import flash.display.Sprite;     import flash.media.Sound;     import flash.net.URLRequest;          public class CuePoints extends Sprite {         private var _sound:Sound;         private var _cuePoints:Array;                  public function CuePoints(  ) {             _cuePoints = [0, 10000, 30000, 68000, 120000];             _sound = new Sound(new URLRequest("song.mp3"));             // Play from the third cuepoint (30 seconds in)             playCuePoint(2);         }                  public function playCuePoint(index:int):void {             _sound.play(_cuePoints[index]);         }              }     }

Of course, in a full application you would have buttons or some other user interface element allowing the user to choose a cue point, which would then pass the index to the playCuePoint( ) method.

Recipe 15.1 explains the functionality to create a pause/restart function in a sound player.

See Also

Recipes 15.1 and 15.2




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net