---
title: "Audio"
description: "Capture from a microphone, process audio in Python in exactly the shape you ask for, play it back, and line it up with video."
type: "docs-page"
url: "https://tatolab.com/docs/build/audio"
site: "Tatolab"
section: "Build in code"
---

# Audio

> Capture from a microphone, process audio in Python in exactly the shape you ask for, play it back, and line it up with video.

Audio works like video: modules handle the devices, your nodes do the work in between, and everything shares one clock. Audio travels as `Channels` blocks, and a Python node reads a block's samples as a numpy array.

## The audio modules

| Module | Node | Does | Ports |
|---|---|---|---|
| `tatolab-microphone` | `MicrophoneSource` | Captures from an input device | out: `audio` |
| `tatolab-speaker` | `SpeakerSink` | Plays to an output device | in: `audio` |
| `tatolab-opus` | `OpusEncoder` | Compresses audio with Opus | in: `audio`, out: `encoded_audio` |
| `tatolab-opus` | `OpusDecoder` | Decompresses Opus back into audio | in: `encoded_audio`, out: `audio` |

Add them to a project with `uv add tatolab-microphone tatolab-speaker`, or from **File › Marketplace…** in Tato Studio. Each runs in its own helper process and moves its samples on a native thread, through the engine's audio backend: PipeWire, else ALSA, on Linux, and CoreAudio on macOS. No interpreter sits in the sample path.

Both device nodes take a `device_id` setting and use the default device without one. On a machine with no audio backend, such as a container, `MicrophoneSource` produces silence and `SpeakerSink` discards what it's given, so the same stream still runs. A stream with no microphone node never opens the microphone or asks for access.

## Hear yourself

Make a stream of two nodes, `tatolab.microphone:MicrophoneSource` and `tatolab.speaker:SpeakerSink`, with the microphone's `audio` linked into the speaker's `audio`. In Studio that's two nodes and one link; in the graph document:

```json title="streams/monitor.graph.json"
{
  "asset": "5d1e0c3a-9b7f-4a2e-8c6d-2f1b0a9e8d7c",
  "display_name": "monitor",
  "nodes": [
    { "id": "8f0e1d2c-3b4a-4596-8778-695a4b3c2d1e", "name": "microphone", "type": "tatolab.microphone:MicrophoneSource" },
    { "id": "1a2b3c4d-5e6f-4708-9a1b-2c3d4e5f6a7b", "name": "speaker", "type": "tatolab.speaker:SpeakerSink" }
  ],
  "links": [
    {
      "source": { "node": "8f0e1d2c-3b4a-4596-8778-695a4b3c2d1e", "port": "audio" },
      "target": { "node": "1a2b3c4d-5e6f-4708-9a1b-2c3d4e5f6a7b", "port": "audio" }
    }
  ]
}
```

Wear headphones: with speakers, the microphone hears them and the sound feeds back. On a Mac, playing the stream asks for microphone access; audio starts once you allow it.

`SpeakerSink` plays blocks of any rate, channel count and sample type: the engine converts each to 48 kHz stereo `f32` on the way in. A period the graph had no samples for plays as silence and is counted.

## Audio blocks

A read through a `Channels` input returns a `ChannelsBlock`:

| Attribute | Meaning |
|---|---|
| `block.sample_rate` | Samples per second, per channel |
| `block.channel_count` | Number of channels |
| `block.samples_per_channel` | Samples per channel in this block |
| `block.dtype` | `"f32"` or `"f64"` |
| `block.timestamp_ns` | The instant of the block's first sample, on the stream's clock |
| `block.start_sample` | The index of the block's first sample in its stream |

`numpy.from_dlpack(block)` reads the samples as a `[channel][sample]` array, without a copy. The read lasts only for the `process` call it was made in; copy what you keep, with `numpy.array(...)`.

## Ask for the shape you want

A microphone opens at whatever rate and channel count the device likes: 44.1 kHz stereo on one machine, 48 kHz mono on the next. Instead of handling every case, an input states a **window contract**, and the runtime resamples, mixes and frames what arrives before your node reads it:

```python
from tatolab.stream import AudioWindowContract, Channels, Input

WINDOW = AudioWindowContract(sample_rate=48_000, channels=1, dtype="f32", window_size=480)

    audio = Input(Channels, delivery="ordered", window=WINDOW)
```

Every block that input reads is exactly 480 mono `f32` samples at 48 kHz, 10 ms, whatever the device opened at. The `microphone-reverb-speaker` example uses one so its filter lengths can be fixed; `audio-mixer-demo` mixes three voices at three different rates into one chord, with no resampler in its code.

Use `delivery="ordered"` for audio: every block, in order.

## Example: a level meter

```python title="nodes/level_meter.py"
import numpy
from tatolab.stream import (
    AudioWindowContract,
    Channels,
    Input,
    Output,
    Records,
    RuntimeContextLimitedAccess,
    node,
)

WINDOW = AudioWindowContract(sample_rate=48_000, channels=1, dtype="f32", window_size=4_800)


@node.meta(category="Audio", description="The loudness of each 100 ms, in dBFS.")
@node.process
class LevelMeter:
    audio = Input(Channels, delivery="ordered", window=WINDOW)
    level = Output(Records, names=("dbfs",))

    def process(self, ctx: RuntimeContextLimitedAccess) -> None:
        while (block := ctx.inputs.read(self.audio)) is not None:
            samples = numpy.from_dlpack(block)[0]
            rms = float(numpy.sqrt(numpy.mean(samples * samples)))
            dbfs = 20.0 * numpy.log10(max(rms, 1e-9))
            ctx.outputs.write(self.level, {"dbfs": round(dbfs, 1)}, timestamp_ns=block.timestamp_ns)
```

## Writing audio

An `Output(Channels, rate=48_000, dtype="f32")` port writes a `[channel][sample]` array, C-contiguous `float32` or `float64`, with the index of its first sample:

```python
ctx.outputs.write(
    self.audio_out,
    samples,                       # shape (channels, samples_per_channel)
    timestamp_ns=first_sample_ns,
    start_sample=self.samples_written,
)
self.samples_written += samples.shape[1]
```

`rate` can come from a setting, `rate=from_config("sample_rate")`. A source paces itself: a `continuous` node with a short `interval_ms` writes however many whole blocks elapsed time owes, as `audio-mixer-demo`'s `ToneSource` does.

## Example: an echo

```python title="nodes/echo.py"
from dataclasses import dataclass

import numpy
from tatolab.stream import AudioWindowContract, Channels, Input, Output, RuntimeContextLimitedAccess, node

RATE = 48_000
WINDOW = AudioWindowContract(sample_rate=RATE, channels=1, dtype="f32", window_size=480)


@dataclass
class EchoConfig:
    delay_seconds: float = 0.3
    feedback: float = 0.4


@node.meta(category="Audio", description="Repeats what it hears, quieter each time.")
@node.process
class Echo:
    audio_in = Input(Channels, delivery="ordered", window=WINDOW)
    audio_out = Output(Channels, rate=RATE, dtype="f32")

    def __init__(self, config: EchoConfig) -> None:
        self.feedback = config.feedback
        self.ring = numpy.zeros(int(config.delay_seconds * RATE), dtype=numpy.float32)
        self.position = 0
        self.written = 0

    def process(self, ctx: RuntimeContextLimitedAccess) -> None:
        while (block := ctx.inputs.read(self.audio_in)) is not None:
            dry = numpy.from_dlpack(block)[0]
            out = numpy.empty_like(dry)
            for i, sample in enumerate(dry):
                delayed = self.ring[self.position]
                out[i] = sample + delayed * self.feedback
                self.ring[self.position] = out[i]
                self.position = (self.position + 1) % self.ring.size
            ctx.outputs.write(
                self.audio_out,
                out[numpy.newaxis, :],
                timestamp_ns=block.timestamp_ns,
                start_sample=self.written,
            )
            self.written += out.size
```

Link the microphone into `audio_in` and `audio_out` into the speaker. A per-sample Python loop is fine at 48 kHz mono; for heavier work, vectorise it with numpy, as the reverb example does.

## Audio with video

Every block is stamped with the instant of its first sample, and every frame with its capture, on the same stream clock. To line them up, compare stamps: a node that reads both keeps the newest frame and the blocks since it, and pairs them by `timestamp_ns`. To send both to a WebRTC endpoint or a MoQ relay, encode each, `H264Encoder` and `OpusEncoder`, and send both encoded outputs; see [WebRTC](https://tatolab.com/docs/build/webrtc) and [Share between streams](https://tatolab.com/docs/share/between-streams).

## Speech to text, and other models

A speech model is a node like any other. Give its input a window contract at the rate the model wants, 16 kHz mono for most, collect windows until you have enough, run the model, and write the text as Records. Run the model in `process`; its own process absorbs the wait, so the rest of the stream doesn't.
