Plays one audio file (.wav, .mp3, .ogg), or an effect made from a preset, and hands back
the controls for it.
What it is for: sound effects (a jump, a coin, a bat hitting the ball), an ambience that loops
(rain, a crowd, an engine), and music that is a single recording. Not for: music in layers that
come in and out (that is useMusic), or a tune written as notes in a .song (that is useSong).
It loads the file itself when given { src }, so one line is enough:
useSound({ src: '/sfx/jump.wav' }).
Called in the body of a scene, like every hook; the controls are used whenever, from an update, a
click, a signal. When the scene stops or the object that asked for it is destroyed, its sound
stops: a level's music does not survive the level.
A one-off (the default) can sound on top of itself, which is what effects need: two coins picked
up at once are heard twice. A looping sound is a single thing that pause, resume and stop
act on: music, rain, an engine.
With spatial it is heard from where the object that asked for it is, and follows it; with zone
it fills an area around the object instead, the way birds fill a meadow. Starting and stopping
can fade, and so can the volume.
Pausing the game or the scene does not stop a sound, because a menu over a frozen level often
wants the music to carry on. To silence something on pause, listen with useScene().onPaused or
useGame().onPaused and decide for each sound.
A sound laid out in a scene document (a sound component, chosen in an editor) is made by this same
hook; a behaviour gets its controls with soundOf(box, name). In a scene shown rather than played
(an editor's viewport), autoplay waits for the game to play.
Example
export const Level: TSceneFn = () => {
const music = useSound({ src: '/audio/theme.mp3' }, { channel: 'music', loop: true, autoplay: true });
const jump = useSound({ src: '/audio/jump.mp3' }, { volume: 0.6 });
const keys = useKeyboard();
useUpdate(() => {
if (keys.justPressed('Space')) jump.play();
});
useScene().onPaused(() => music.setVolume(0.2));
return createScene();
};