Previous Page
Next Page

Recipe 15.5. Playing a Sound Multiple Times (Looping)

Problem

You want to play a sound file more than once, or have it play over and over in a continuous loop.

Solution

Set a looping value in the play( ) method.

Discussion

When you play a sound, it only plays oncefrom beginning to endby default. There may be cases when you want to have the sound play more than once, or even play continuously. For example, you may have a short music loop for the background to a game or for a web site. You can set this loop to play continuously so it sounds like one long song.

The way to set the number of loops (or times) to play is by passing in a value as the second parameter of the play( ) method. Of course, if you do this, you'll also have to set a value for the optional first parameter of the start offset (see Recipe 15.1). If you don't want to offset the start of the sound, but want to use the loop parameter, just pass zero as the first parameter, like so:

_sound.play(0, 3);

This plays the sound file from the very beginning (zero offset) and loops it three times.

The minimum sensible value you can set for a loop is one, which causes the sound to play only once. If you pass in zero (or even a negative number), the sound still plays only one time.

There is no automatic way to cause the sound to loop forever; however, you can pass a very high value. An easy solution is to pass in int.MAX_VALUE, which is the highest value that an integer variable can hold, and is equal to 2,147,483,647. Even if your sound was only one second long, this would cause it to play for almost 70 years, which is pretty safe to call "continuously."

See Also

Recipes 15.1 and 15.2


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)