Skip to main content

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​

ParameterTypeDefaultDescription
idstringrequiredID of the sound or stream.
loopbooleanrequiredtrue to loop, false to play to the end and stop.
maxLoopsnumber-1How 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​

Try it

Turn looping on and off

Idle

Press 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 for play() with loop and maxLoops, which calls setLoop for you.
  • Leaving out maxLoops sets it back to -1, so setLoop('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 seamlessLoop instead. On a seamless loop setLoop switches the loop of the playing source directly.
  • On a stream from loadStream this sets the media element's loop, and maxLoops is ignored.
  • No event is dispatched. An id that is not loaded is ignored quietly.

See also​

  • getLoop: read whether a sound loops.
  • PlayOptions: set loop, maxLoops and seamlessLoop when you play.
  • soundEvents: the loop_completed event fires after each pass.