Skip to main content

setSoundSprite

Define sprites on a loaded sound: named ranges, each with a start and end time in seconds. Reach for it when many short effects live in one audio file and you want to play them by name with playSprite.

setSoundSprite(id: string, sprite: { [key: string]: [number, number] }): void;

Parameters​

ParameterTypeDefaultDescription
idstringrequiredID of a sound loaded with loadSound. Its buffer must be decoded already.
sprite{ [key: string]: [number, number] }requiredOne entry per sprite: the key is its name, the value is [start, end] in seconds.

Returns​

Nothing.

Example​

import { SoundHub } from 'soundhub';

const soundHub = new SoundHub();
await soundHub.loadSound('game-sounds', '/audio/8-bit-game-sounds.mp3');

soundHub.setSoundSprite('game-sounds', {
jump: [4.5, 5.5],
powerUp: [2.5, 4.5],
fail: [6, 8.5],
});

// A second call adds to the config
soundHub.setSoundSprite('game-sounds', { victory: [20.5, 22.5] });

soundHub.playSprite('game-sounds', 'jump');
soundHub.getSpriteConfig('game-sounds');
// { jump: [4.5, 5.5], powerUp: [2.5, 4.5], fail: [6, 8.5], victory: [20.5, 22.5] }

Good to know​

  • Since 6.3.2 a second call adds to the recorded config instead of replacing it, so you can register sprites a few at a time. Setting a key that already exists replaces that sprite: the old sprite sound and all its playing instances are stopped and taken off the master first.
  • Each sprite becomes a sound of its own with the id <id>_<key>, for example 'game-sounds_jump'. The samples are copied into a new buffer. You can pass that id to stop, setSoundVolume or an event filter.
  • A sprite starts with the volume, pan and play options the owner sound has at the moment you call this. Later changes to the owner do not carry over.
  • Times are clamped to the length of the buffer. A range that ends up empty (for example one that starts past the end of the file) is skipped with a debug log, but its key is still recorded in the config.
  • Every sprite that is created dispatches SoundEventsEnum.SPRITE_SET ('sprite_set') with the sprite id as soundId. For a stream from loadStream this method throws, because sprites need the samples in memory. For an id that is not loaded yet, the error is logged, stored for getLastError and dispatched as an error event.

See also​