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
| Parameter | Type | Default | Description |
|---|---|---|---|
id | string | required | ID of a loaded sound or stream. |
options | PlayOptions | {} | Options for this play. See PlayOptions for every field. |
skipDispatchEvent | boolean | false | When 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
Play with options
IdleEdit 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 laterplay('music')loops too. - Without
overlap, callingplay()on a sound that is already playing restarts it fromstartTime. On a paused sound it carries on from the paused position, but dispatchesstartedrather thanresumed. Useresumefor that. - A sound muted with
mutestays muted when you play it. Avolumepassed while muted is kept forunmute, andfadeInDurationandfadeOutDurationdo not run. Before 6.4.0 a fresh play ended the mute. - A
groupIdmust belong to a group made withcreateSoundGroup. If it does not, nothing plays and no error is reported. - A variation name from
createVariationsplays one of its takes and returns that take'sSound. Added in 6.5.0 - For a stream from
loadStreamonlyvolume,pan,loop,playbackRate,startTimeandtrackProgressare used. For an id that is not loaded, the error is logged, stored forgetLastErrorand dispatched as anerrorevent.
See also
PlayOptions: every option you can pass.playSprite: play one sprite out of a sound.pause,stop: halt the sound again.soundHubConfig: set defaults for every sound.