# Sound and spatial audio

> useLoadAudio loads a clip like a texture and useSound plays it: overlapping effects, music on its own channel and a sound crossing the screen with the bird.

Example `audio`, running at https://nacatamalon.com/en/examples/audio. The whole catalogue: https://nacatamalon.com/llms/examples.md.

`useLoadAudio` loads a clip like a texture and `useSound` hands back the controls. A one-off effect sounds on top of itself; a looping one is a single sound you `pause` and `resume`. Each one belongs to a channel, and `useAudio` moves those volumes: the sliders of an options screen. **Click a coin** (the first click is also what lets the browser make noise), **M** toggles the ambience, and the **arrows** move the music volume.

The bird carries a `spatial: true` sound, so it crosses from one ear to the other and fades with distance, measured in pixels from the middle of what the camera shows. **P** pauses the level: the engine never silences anything by itself, it only says so through `useScene().onPaused`, and this example stops the birds while the ambience carries on.

## Code

`index.ts`:

```ts
import { PauseMenu } from './scenes/menu';
import { createGame } from 'nacatamalon';
import * as Settings from './settings';
import { Level } from './scenes/demo';

const game = createGame('#app', {
    width: Settings.WIDTH,
    height: Settings.HEIGHT,
    background: '#0a0a12'
});

// Declare Scenes
game({
    Level,
    PauseMenu
}, 'Level');
```

`components/bird.ts`:

```ts
import { createSprite, useLoadTexture, useScene, useSound, useUpdate } from 'nacatamalon';

import type { TCamera2d } from 'nacatamalon';

export const Bird = (camera: TCamera2d) => {
    const gammix = useLoadTexture({
        src: '/example-assets/assets/gammix.png'
    });

    // A placed sound: distances are pixels of the game, measured from the middle of what the
    // camera shows. It is heard where this object is, which is where its bird is.
    const bird = createSprite({
        texture: gammix,
        width: 40,
        height: 40,
        transform: {
            x: 40,
            y: 90
        }
    });

    const song = useSound({
        src: '/example-assets/audio/birds.mp3'
    }, {
        loop: true,
        volume: 0.5,
        spatial: true,
        refDistance: 60,
        maxDistance: 700,
        autoplay: true,
    });

    // The engine never silences anything on its own: a paused level usually wants its music to
    // carry on. It only says what happened, and the game decides. Here the birds stop and the
    // ambience stays.
    const level = useScene();

    level.onPaused(() => song.pause());
    level.onResumed(() => song.resume());

    useUpdate((_delta, elapsed) => {
        bird.transform.x = 240 + Math.sin(elapsed * 0.7) * 260;
        // The camera drifts, so the bird moves against it too: the listener goes with the view.
        camera.transform.x = Math.sin(elapsed * 0.3) * 60;
    });
};
```

`components/hud.ts`:

```ts
import { createSprite, createText, listen, useAudio, useKeyboard, useLoadAudio, useLoadBitmapFont, useScene, useScreenSpace, useSound, useUpdate } from 'nacatamalon';
import * as Settings from '../settings';

export const Hud = () => {
    useScreenSpace();

    const font = useLoadBitmapFont(Settings.ARCADE);
    const keys = useKeyboard();
    const scene = useScene();
    const audio = useAudio();

    // An effect: every play() is a new one, so two coins at once are heard twice.
    const coin = useSound(useLoadAudio({
        src: '/example-assets/audio/coin.mp3',
        key: 'coin'
    }), {
        volume: 0.7
    });

    for (let i = 0; i < 3; i++) {
        const money = createSprite({
            tint: Settings.YELLOW,
            width: 28,
            height: 28,
            transform: {
                x: 120 + i * 90,
                y: 210
            },
            onClick: () => coin.play(),
        });

        listen(money, {
            onPointerOver: () => {
                money.tint = Settings.WHITE;
            },
            onPointerOut: () => {
                money.tint = Settings.YELLOW;
            }
        });
    }

    // Music: a single sound that pause, resume and stop act on. Its own channel, so its volume
    // moves without touching the effects.
    const ambience = useSound({
        src: '/example-assets/audio/outdoor_ambience.mp3'
    }, {
        channel: 'music',
        loop: true
    });

    let ambienceOn = false;

    // Where the music channel starts. A game with an options screen reads this from its store
    // instead, so the volumes are still there next time.
    audio.setVolume(0.6, 'music');

    createText({
        text: 'CLICK A COIN',
        font,
        style: {
            fontSize: 8
        },
        tint: Settings.WHITE,
        anchor: {
            x: 0.5,
            y: 0
        },
        transform: {
            x: 240,
            y: 250
        }
    });
    createText({
        text: 'M MUSIC   ARROWS VOLUME   P PAUSE',
        font,
        style: {
            fontSize: 8
        },
        tint: Settings.WHITE,
        anchor: {
            x: 0.5,
            y: 0
        },
        transform: {
            x: 240,
            y: 268
        }
    });

    const label = createText({
        text: '',
        font,
        style: {
            fontSize: 8
        },
        tint: Settings.YELLOW,
        transform: {
            x: 20,
            y: 20
        }
    });

    // The volume bar of the music channel.
    createSprite({
        tint: '#2a2740',
        anchor: {
            x: 0,
            y: 0.5
        },
        width: 120,
        height: 10,
        transform: {
            x: 20,
            y: 44
        }
    });

    const bar = createSprite({
        tint: Settings.YELLOW,
        anchor: {
            x: 0,
            y: 0.5
        },
        width: 0,
        height: 10,
        transform: {
            x: 20,
            y: 44
        }
    });

    useUpdate(() => {
        if (keys.justPressed('m')) {
            ambienceOn = !ambienceOn;

            if (ambienceOn) {
                ambience.play();
            } else {
                ambience.stop();
            }
        }

        // Named keys keep their name: 'ArrowUp', not 'arrowup'.
        if (keys.justPressed('ArrowUp')) {
            audio.setVolume(Math.min(1, audio.getVolume('music') + 0.1), 'music');
        }

        if (keys.justPressed('ArrowDown')) {
            audio.setVolume(Math.max(0, audio.getVolume('music') - 0.1), 'music');
        }

        // Pausing the scene freezes this very update, so the menu launched over it reads the key
        // that resumes it.
        if (keys.justPressed('p')) {
            scene.launch('PauseMenu');
            scene.pause();
        }

        bar.width = audio.getVolume('music') * 120;
        label.text = 'MUSIC ' + (ambienceOn ? 'ON' : 'OFF');
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useCamera2d, useSpawn } from 'nacatamalon';

import { Bird } from '../components/bird';
import { Hud } from '../components/hud';

export const Level = () => {
    const camera = useCamera2d();

    useSpawn(Bird)(camera);
    useSpawn(Hud)();

    return createScene();
};
```

`scenes/menu.ts`:

```ts
import { createScene, createText, useKeyboard, useLoadBitmapFont, useScene, useUpdate } from 'nacatamalon';
import * as Settings from '../settings';

export const PauseMenu = () => {
    const font = useLoadBitmapFont(Settings.ARCADE);
    const keys = useKeyboard();
    const scene = useScene();

    createText({
        text: 'PAUSED',
        font,
        style: {
            fontSize: 16
        },
        tint: Settings.WHITE,
        anchor: {
            x: 0.5,
            y: 0.5
        },
        transform: {
            x: 240,
            y: 150
        }
    });

    useUpdate(() => {
        if (keys.justPressed('p')) {
            // The level by its name, then this menu closes: launch's other half.
            scene.resume('Level');
            scene.stop();
        }
    });

    return createScene();
};
```

`settings.ts`:

```ts
import { getColor } from 'nacatamalon';

export const ARCADE = {
    json: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.json',
    atlas: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.png'
};
export const WHITE = getColor('#ffffff');
export const YELLOW = getColor('#f5c518');
export const WIDTH = 480;
export const HEIGHT = 300;
// The coins, the texts and the volume bar are pinned to the screen: the camera below drifts, and
// a button that slides away while you aim at it is nobody's idea of a button.
```
