# sound

Part of the [scripting reference](index.md), written by the engine so it matches your `frost`. Start with [your first game](../start/first-game.md) if you are new.

Use when playing a sound on hit, adding sound effects or music, adjusting volume, fading or positioning audio.

| In a script | Does |
| --- | --- |
| `sound.play("hit.wav", { volume = 1, pitch = 1, vary = 0, at = entity })` | Plays a sound once. The table and its keys are optional; in 3D `near` and `far` too (see Sound) |
| `sound.volume(level)` | Sets the gain of everything heard, 0 to 1 |
| `sound.effects(level)` | Sets the gain of all that `sound.play` plays, 0 to 1 |
| `music.play("theme.ogg", { volume = 1 })` | Loops a sound as the one music track, in place of the track before |
| `music.stop(seconds)` | Stops the music, fading out evenly over `seconds` (left out, or held: at once) |
| `music.pause()`, `music.resume()` | Holds the music where it is, and lets it go on. Sounds play on. `music.play` lets go of a hold |
| `music.volume(level, seconds)` | Moves the music's own volume, 0 to 1, to `level` evenly over `seconds` (left out: at once). It outlasts the track |

### Sound

Sound is output: a script cannot read what was heard, and a request is
not in the world, the checksum or a snapshot.

A sound is named as the project lists it under `sounds`: a WAV or Ogg Vorbis file. An
Ogg file over ten seconds is decoded as it plays: only `music.play` takes it. A volume
is 0 to 1 and a pitch is a speed, 0.25 to 4; outside its range is an error, not a
clamp. `vary = 0.1` draws each play's pitch within a tenth of `pitch` from the game's
random source, so adding it to a script moves the `math.random` numbers after it.
`at = entity` or `x = 40` puts a play left or right by that world x against the
camera, once. In 3D, `at = entity` uses the thing's position relative to the viewing
camera at request time (`Follow` placed it at the previous step's end). Pan follows
distance along camera-right: behind-left stays left regardless of camera direction.
The distance fade multiplies `volume`: full within `near` metres, silent past `far`,
linear between. Defaults: `[sound]`, else 2 and 30; overrides in a play's table:
`near = 1, far = 12`. Requests carry computed results: recordings sound the same
on every machine and in a browser. At most 4 of one sound and 32 in all are heard: one
more eases out the quietest, the oldest on a tie. A playing sound has no handle and no
stop. The calls work at a script's top level too, which a reload runs again.

Volumes multiply. A settings screen's sliders write `music.volume` and
`sound.effects`. To cross from one track to the next: `music.stop(1)`, then a second
later `music.play("next.ogg")`. A fade is at most 60 seconds.

```toml
# Optional 3D `sound.play` range for `at`: full within `near` metres of the viewing
# camera, silent past `far`, linear between. Per-play `near` and `far` override these
# defaults.
[sound]
near = 2
far = 30
```
