> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nanoforge.eu/llms.txt
> Use this file to discover all available pages before exploring further.

# Sound and music

> Play sound effects and background music

Two client libraries play audio:

| Library | Package | Context key | For |
| - | - | - | - |
| `SoundLibrary` | `@nanoforge-dev/sound` | `ctx.sound` | Sound effects. Several can play at the same time. |
| `MusicLibrary` | `@nanoforge-dev/music` | `ctx.music` | Music. Playing a track stops the one before it. |

Both have the same three methods: `load(key, url)`, `play(key)` and `mute()`.

## Load your files

Put the audio files in your project's `assets` folder, then load each one under a key after `app.init`:

```ts theme={null}
const app = NanoforgeFactory.createClient();
const sound = new SoundLibrary();
const music = new MusicLibrary();
app.use(sound);
app.use(music);

await app.init(options);

// `main` has no context: read the URLs of the files in `assets/` from the run options.
const url = (path: string): string => {
  const file = options.files.get(path);
  if (!file) throw new Error(`Missing asset: ${path}`);
  return file;
};
sound.load("jump", url("/jump.wav"));
music.load("theme", url("/theme.mp3"));
music.play("theme");

await app.run();
```

## Play

From a system, or anywhere you have the context:

```ts theme={null}
if (ctx.input.isKeyPressed(InputEnum.Space)) ctx.sound.play("jump");
```

* `ctx.music.play(key)` stops the track that was playing before.
* `play` throws `NfNotFound` when no file was loaded under that key.
* Playing a sound that is already playing has no effect until it ends.

## Turn the sound on

> [!WARNING]
>
> Both libraries start **muted**, and `mute()` toggles the muted state: call it once to turn the
> sound on. Browsers also block audio until the player has interacted with the page, so tie it to a
> key press or a click.

A system runs on every tick, so toggle on the press, not while the key is held:

```ts theme={null}
let wasPressed = false;

// Toggles sound and music once per press of M.
export const toggleSound = (_registry: Registry, ctx: Context) => {
  const pressed = ctx.input.isKeyPressed(InputEnum.KeyM) ?? false;
  if (pressed && !wasPressed) {
    ctx.sound.mute();
    ctx.music.mute();
  }
  wasPressed = pressed;
};
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.