Skip to content

Sound ​

Sound plays sounds with the Web Audio API: audio files by URL, loaded once and cached, and short synthesized tones for feedback without any files. Everything goes through one master volume.

ts
import { 
Sound
} from "@pawnjs/core";
const
sound
=
engine
.
plugin
(
Sound
);
await
sound
.
load
("/sounds/coin.mp3"); // optional: avoids a late first play
sound
.
play
("/sounds/coin.mp3", {
volume
: 0.6,
rate
: 1.2 });
sound
.
tone
({
frequency
: 880,
to
: 1320,
duration
: 0.1,
wave
: "square" });
sound
.
volume
= 0.5;
sound
.
muted
= true;
  • play(url, { volume, rate }) loads the file when needed; rate 2 is an octave up. A file that fails to load logs a warning and is tried again on the next call.
  • tone({ frequency, to, duration, wave, volume }) plays a tone that fades out over duration seconds, sliding from frequency to to Hz. wave is "sine", "square", "triangle" or "sawtooth".
  • Browsers start audio suspended until the page gets a press. Sound resumes it on the first pointer or key press (enableUnlock, on by default); sounds played before that are dropped rather than all played at once later.
  • Without Web Audio (a test, a server) Sound stays silent, so the same code runs headless. Pass context to play into an AudioContext of your own.

Your own sounds ​

For a sound that runs and changes with the game, like an engine whose pitch follows its speed, build a Web Audio graph on sound.context and connect it to sound.destination, so it follows volume and muted:

ts
const 
sound
=
engine
.
plugin
(
Sound
);
const {
context
,
destination
} =
sound
;
if (
context
&&
destination
) {
const
hum
=
context
.
createOscillator
();
hum
.
type
= "sawtooth";
const
gain
=
context
.
createGain
();
gain
.
gain
.
value
= 0.1;
hum
.
connect
(
gain
).
connect
(
destination
);
hum
.
start
();
engine
.
addSystem
(() => {
// Until a press, time stands still and changes would only pile up. if (
context
.
state
!== "running") return;
// Glide toward the new pitch rather than jump each frame.
hum
.
frequency
.
setTargetAtTime
(60 +
car
.
speed
* 4,
context
.
currentTime
, 0.05);
}); }

Both are null without Web Audio. A source started before the page is pressed waits, and is heard once audio is unlocked. Audio also keeps playing in a hidden tab, where systems stop running: turn a running sound down on visibilitychange.

SoundOn plays a sound on an entity event; see Behaviors.