setLoop
Switch looping on or off for a sound. Pass maxLoops to stop after a set number of plays.
setLoop(id: string, loop: boolean, maxLoops?: number): void;
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
id | string | required | ID of the sound or stream. |
loop | boolean | required | true to loop, false to play to the end and stop. |
maxLoops | number | -1 | How many times the sound plays in total, counting the first play. 0 or -1 loops forever. |
Returns
Nothing.
Example
import { SoundHub } from 'soundhub';
const soundHub = new SoundHub();
await soundHub.loadSound('music', '/audio/theme.mp3');
// Loop forever
soundHub.setLoop('music', true);
soundHub.play('music');
// Stop looping: the current pass plays to the end
soundHub.setLoop('music', false);
// Play three times in total, then stop
soundHub.setLoop('music', true, 3);
soundHub.play('music');
Try it
Turn looping on and off
IdlePress Play, then flip Loop while it sounds. The change applies to the sound that is already playing.
Code
Your clicks show up here as soundhub calls
Good to know
- The setting is stored in the sound's play options, so it also applies to the next
play(). The same goes forplay()withloopandmaxLoops, which callssetLoopfor you. - Leaving out
maxLoopssets it back to-1, sosetLoop('music', true)also clears an earlier limit. - A normal loop restarts the sound at the end, which leaves a small gap. For a bed or a drone, where the gap is audible, play with
seamlessLoopinstead. On a seamless loopsetLoopswitches the loop of the playing source directly. - On a stream from
loadStreamthis sets the media element'sloop, andmaxLoopsis ignored. - No event is dispatched. An id that is not loaded is ignored quietly.
See also
getLoop: read whether a sound loops.PlayOptions: setloop,maxLoopsandseamlessLoopwhen you play.soundEvents: theloop_completedevent fires after each pass.