Recipe 15.3.
Setting the Buffer for a Sound
Problem
You
want to ensure that a
streaming sound plays smoothly.
Solution
Set a buffer time by using the SoundLoaderContext class.
Discussion
The Sound class streams audio as it
plays, which means that a sound starts playing before it is fully
downloaded. This is especially useful for larger sound files, such
as full songs, which can be several megabytes in size.
Depending on how your sound is encoded and the
available bandwidth, a sound may be playing faster than it is
downloading. In this case, the sound may pause while it waits for
more sound data to load in. To safeguard against this, you can set
a buffer. This causes the Sound object to pre-load a certain
amount of sound data before it starts playing. Then, if there is a
momentary slowdown in bandwidth, the sound can keep playing the
buffered data without pausing.
By default, a Sound object creates a
one-second buffer when you tell it to load a sound file. In other
words, even if you tell it to play immediately, the Sound
object waits until at least one second's worth of sound data has
come in. Additionally, if that buffer is used up and the sound
needs to stop to wait for more data, it refills that one-second
buffer before it resumes playing again.
If you are unsure of network conditions or have
sound files that were encoded at a high bitrate (requiring more
bits of information per second of playing time), then you may want
to increase the size of this buffer to ensure smoother playback.
You do this by creating a SoundLoaderContext object, passing
in the size of the buffer, in milliseconds, to the constructor. For
example, if you wanted to create a five-second buffer, you would do
the following:
buffer = new SoundLoaderContext(5000);
You can use this object for either method of
loading a soundin the constructor of the Sound object, or in
the load( ) method (see Recipe
15.1). Just pass it in as the second parameter after the
URLRequest parameter, as shown here:
var request:URLRequest = new URLRequest("song.mp3");
var buffer:SoundLoaderContext = new SoundLoaderContext(5000);
_sound = new Sound(request, buffer);
_sound.play( );
or:
var request:URLRequest = new URLRequest("song.mp3");
var buffer:SoundLoaderContext = new SoundLoaderContext(5000);
_sound = new Sound( );
_sound.load(request, buffer);
_sound.play( );
See Also
Recipe
15.1 for information on how to load external sound files.
|