Skip to main content

play

Start a loaded sound. This is the method you call most: pass the id, and optionally a PlayOptions object to set the volume, loop, fades, pan and more for this play.

play(id: string, options?: PlayOptions, skipDispatchEvent?: boolean): Sound | undefined;

Parameters​

ParameterTypeDefaultDescription
idstringrequiredID of a loaded sound or stream.
optionsPlayOptions{}Options for this play. See PlayOptions for every field.
skipDispatchEventbooleanfalseWhen true, no started event is dispatched.

Returns​

Sound | undefined: the sound that started. With overlap: true this is the new instance, whose id is <id>:<n>. You get undefined for a stream, for an id that is not loaded, and for a groupId that has no group.

Example​

import { SoundHub } from 'soundhub';

const soundHub = new SoundHub();
await soundHub.loadSound('music', '/audio/theme.mp3');

soundHub.play('music', {
volume: 0.8,
loop: true,
fadeInDuration: 2,
});

// Later
soundHub.stop('music');

Overlapping instances for short effects:

await soundHub.loadSound('click', '/audio/click.mp3');

const first = soundHub.play('click', { overlap: true }); // id 'click:1'
const second = soundHub.play('click', { overlap: true }); // id 'click:2', plays on top

Try it​

Try it

Play with options

Idle

Edit the options, then press Play. They go to play() exactly as written.

Try playbackRate or volume. With "seamlessLoop": true the loop has no gap, and maxLoops no longer applies: it runs until you stop it.

Code
Your clicks show up here as soundhub calls

Good to know​

  • The options are merged into the sound's stored play options and stay there. After play('music', { loop: true }), a later play('music') loops too.
  • Without overlap, calling play() on a sound that is already playing restarts it from startTime. On a paused sound it carries on from the paused position, but dispatches started rather than resumed. Use resume for that.
  • A sound muted with mute stays muted when you play it. A volume passed while muted is kept for unmute, and fadeInDuration and fadeOutDuration do not run. Before 6.4.0 a fresh play ended the mute.
  • A groupId must belong to a group made with createSoundGroup. If it does not, nothing plays and no error is reported.
  • A variation name from createVariations plays one of its takes and returns that take's Sound. Added in 6.5.0
  • For a stream from loadStream only volume, pan, loop, playbackRate, startTime and trackProgress are used. For an id that is not loaded, the error is logged, stored for getLastError and dispatched as an error event.

See also​