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

# Retrieving Audio from A100 Audio Gateway

> Download recorded audio from a Rhombus A100 Audio Gateway using the API — fetch DASH MPD manifests, retrieve segments, and play back audio over WAN VOD.

In this guide, you will learn how to retrieve **recorded audio** from a Rhombus **A100 Audio Gateway** using the Rhombus API. You will:

1. Call the API to get media URI templates
2. Generate a federated session token for WAN playback
3. Download the DASH MPD and audio segments
4. Optionally convert the resulting Opus/WebM audio using ffmpeg

Rhombus exposes media access through **URI templates** rather than returning raw audio bytes directly from a single REST response.

## Prerequisites

<Note>
  All API calls in this guide use the following authentication headers:

  ```http theme={null}
  Content-Type: application/json
  x-auth-scheme: api-token
  x-auth-apikey: YOUR_API_KEY
  ```

  Base URL: `https://api2.rhombussystems.com`
</Note>

**You will need:**

* An A100 Audio Gateway UUID (Rhombus DeviceFacetUuid / RUUID style string)
* Recorded audio that exists and is available (determined by your device licensing and recording configuration)
* A client capable of:
  * Making HTTP requests
  * Parsing XML (for the MPD manifest)
  * Writing binary segment bytes to disk

## Implementation Steps

<Steps>
  <Step title="Get the A100 Audio Gateway Media URIs">
    Call the `getMediaUris` endpoint to retrieve the URI templates for your audio gateway.

    **Endpoint:** `POST /api/audiogateway/getMediaUris`

    ```bash theme={null}
    curl --request POST \
      --url https://api2.rhombussystems.com/api/audiogateway/getMediaUris \
      --header 'Content-Type: application/json' \
      --header 'x-auth-scheme: api-token' \
      --header 'x-auth-apikey: YOUR_API_KEY' \
      --data '{
        "gatewayUuid": "AAAAAAAAAAAAAAAAAAAAAA.v0"
      }'
    ```

    **Relevant response fields:**

    | Field                    | Description                                                 |
    | ------------------------ | ----------------------------------------------------------- |
    | `wanVodMpdUriTemplate`   | WAN VOD MPD template (use this for recorded audio over WAN) |
    | `wanLiveOpusUri`         | WAN live Opus stream URI                                    |
    | `wanLiveMpdUri`          | WAN live MPD URI                                            |
    | `lanVodMpdUrisTemplates` | LAN VOD templates                                           |
  </Step>

  <Step title="Generate a Federated Session Token">
    WAN MPD access requires a short-lived federated session token appended as query parameters.

    **Endpoint:** `POST /api/org/generateFederatedSessionToken`

    ```bash theme={null}
    curl --request POST \
      --url https://api2.rhombussystems.com/api/org/generateFederatedSessionToken \
      --header 'Content-Type: application/json' \
      --header 'x-auth-scheme: api-token' \
      --header 'x-auth-apikey: YOUR_API_KEY' \
      --data '{
        "domain": ".rhombussystems.com",
        "durationSec": 60
      }'
    ```

    **Response:** Returns `federatedSessionToken`

    <Tip>
      Choose a `durationSec` long enough to fetch the MPD and all segments for your requested range. For large pulls (up to 24 hours), increase this value accordingly.
    </Tip>
  </Step>

  <Step title="Build the WAN VOD MPD URL">
    Take the `wanVodMpdUriTemplate` from Step 1 and perform string substitution:

    * Replace `{START_TIME}` with your requested start time (in seconds)
    * Replace `{DURATION}` with your requested duration (in seconds)

    <Warning>
      **Timestamp units matter!**

      Rhombus audio endpoints use **seconds since epoch** (`startTimeSec`, `durationSec`). If your timestamps are stored in milliseconds, convert them:

      ```text theme={null}
      startTimeSec = startTimeMs / 1000
      durationSec = durationMs / 1000
      ```
    </Warning>
  </Step>

  <Step title="Fetch the MPD with the Federated Token">
    Append the authentication query parameters to your MPD URL:

    ```text theme={null}
    <mpdUri>?x-auth-scheme=federated-token&x-auth-ft=<TOKEN>
    ```

    This MPD is a DASH manifest that describes how to fetch the init segment and subsequent audio segments.
  </Step>

  <Step title="Download and Stitch Segments">
    Download the segments in order, appending the same `?x-auth-scheme=federated-token&x-auth-ft=<TOKEN>` query parameters you used for the MPD — the segments are served from the same WAN host and use the same authentication:

    1. **Init segment** (e.g., `seg_init_audio.hdr`)
    2. **Media segments** (e.g., `seg_1.webm`, `seg_2.webm`, ...)

    <Info>
      Segments are **2 seconds each**. Calculate the number of segments:

      ```text theme={null}
      numSegments = durationSec / 2
      ```
    </Info>

    Write the init header bytes followed by each segment's bytes to produce a valid WebM/Opus audio file (48 kHz, mono).
  </Step>
</Steps>

***

## Complete Python Example

This example implements the full workflow described above:

```python theme={null}
import requests

BASE_URL = "https://api2.rhombussystems.com"
API_KEY = "YOUR_API_KEY"

HEADERS = {
    "Content-Type": "application/json",
    "x-auth-scheme": "api-token",
    "x-auth-apikey": API_KEY,
}


def generate_federated_token(domain: str, duration_sec: int) -> str:
    """Generate a short-lived federated session token for WAN access."""
    url = f"{BASE_URL}/api/org/generateFederatedSessionToken"
    resp = requests.post(
        url, headers=HEADERS, json={"domain": domain, "durationSec": duration_sec}
    )
    resp.raise_for_status()
    return resp.json()["federatedSessionToken"]


def get_audio_gateway_media_uris(gateway_uuid: str) -> dict:
    """Get media URI templates for an audio gateway."""
    url = f"{BASE_URL}/api/audiogateway/getMediaUris"
    resp = requests.post(url, headers=HEADERS, json={"gatewayUuid": gateway_uuid})
    resp.raise_for_status()
    return resp.json()


def build_mpd_uri(template: str, start_time_sec: int, duration_sec: int) -> str:
    """Substitute placeholders in the MPD URI template."""
    return template.replace("{START_TIME}", str(start_time_sec)).replace(
        "{DURATION}", str(duration_sec)
    )


def download_wan_vod_audio(
    gateway_uuid: str, start_time_sec: int, duration_sec: int, out_path: str
):
    """Download recorded audio from a Rhombus A100 Audio Gateway."""
    # Step 1: Get media URIs
    media = get_audio_gateway_media_uris(gateway_uuid)
    mpd_template = media["wanVodMpdUriTemplate"]

    # Step 2: Generate federated token
    ft = generate_federated_token(domain=".rhombussystems.com", duration_sec=60)

    # Step 3: Build MPD URL
    mpd_uri = build_mpd_uri(mpd_template, start_time_sec, duration_sec)

    # Step 4: Fetch MPD (authenticated via query string)
    auth_qs = f"?x-auth-scheme=federated-token&x-auth-ft={ft}"
    mpd_resp = requests.get(mpd_uri + auth_qs)
    mpd_resp.raise_for_status()

    # Step 5: Download init segment and media segments.
    # These are served from the same WAN host as the MPD, so authenticate them
    # with the federated token query params — not the API key header.
    init_uri = mpd_uri.replace("file.mpd", "seg_init_audio.hdr")
    num_segments = duration_sec // 2

    with open(out_path, "wb") as f:
        # Download init segment
        init_resp = requests.get(init_uri + auth_qs)
        init_resp.raise_for_status()
        f.write(init_resp.content)

        # Download media segments
        for i in range(1, int(num_segments) + 1):
            seg_uri = mpd_uri.replace("file.mpd", f"seg_{i}.webm")
            seg_resp = requests.get(seg_uri + auth_qs)
            seg_resp.raise_for_status()
            f.write(seg_resp.content)


if __name__ == "__main__":
    gateway_uuid = "AAAAAAAAAAAAAAAAAAAAAA.v0"
    start_time_sec = 1700000000  # Example: November 14, 2023
    duration_sec = 60  # 1 minute (max: 86400 seconds / 24 hours)

    download_wan_vod_audio(
        gateway_uuid=gateway_uuid,
        start_time_sec=start_time_sec,
        duration_sec=duration_sec,
        out_path="rhombus_audio.webm",
    )
    print("Wrote rhombus_audio.webm")
```

## Converting Audio with ffmpeg

The downloaded audio is in **Opus/WebM** format (48 kHz, mono). You can convert it to other formats using ffmpeg:

<CodeGroup>
  ```bash WAV (16-bit PCM) theme={null}
  ffmpeg -i rhombus_audio.webm -acodec pcm_s16le rhombus_audio.wav
  ```

  ```bash MP3 theme={null}
  ffmpeg -i rhombus_audio.webm rhombus_audio.mp3
  ```
</CodeGroup>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Empty manifests or missing segments">
    **Cause:** Template substitution uses wrong time units.

    **Solution:** If your timestamps are in milliseconds but the template expects seconds, convert them:

    ```python theme={null}
    start_time_sec = start_time_ms // 1000
    duration_sec = duration_ms // 1000
    ```
  </Accordion>

  <Accordion title="MPD rewrite doesn't match your template">
    **Cause:** The code assumes the MPD filename is `file.mpd`.

    **Solution:** If your template uses a different filename, adjust the string replacement logic:

    ```python theme={null}
    # Current logic
    init_uri = mpd_uri.replace("file.mpd", "seg_init_audio.hdr")

    # Adjust to match your actual filename
    init_uri = mpd_uri.replace("your_filename.mpd", "seg_init_audio.hdr")
    ```
  </Accordion>

  <Accordion title="Token expires before download completes">
    **Cause:** The federated token duration is too short for large audio pulls.

    **Solution:** Increase `durationSec` when generating the token. For 24-hour pulls, you may need significantly longer durations to fetch all segments.

    ```python theme={null}
    ft = generate_federated_token(domain=".rhombussystems.com", duration_sec=300)  # 5 minutes
    ```
  </Accordion>
</AccordionGroup>

## API Reference

The following endpoints are used in this guide. Visit the [API Reference](/api-reference) tab for full request and response schemas.

* `POST /api/audiogateway/getMediaUris` — Get Media URIs for Audio Gateway
* `POST /api/org/generateFederatedSessionToken` — Generate Federated Session Token
