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

# Fetch Bulk Text-to-Speech Results

> Retrieves the results of multiple Text-to-Speech runs using a list of `run_id` values in a single request.

<Card icon="lightbulb" cta="Go to streaming Text-to-Speech" href="create-tts-stream">
  Bulk retrieval only helps when you already have run IDs from the deprecated async `POST /tts` workflow. For anything new, stream each piece of speech with `POST /tts-stream` (split longer copy into segments if needed) instead of batching legacy runs.
</Card>

This endpoint streamlines the process of retrieving multiple completed audio files at once, perfect for applications that process batches of text-to-speech tasks. Instead of making individual requests for each `run_id`, you can efficiently gather all your generated audio files in a single API call.

## How to Use this Endpoint

Retrieving multiple generated audio files is straightforward - make a `POST` request to this endpoint with an array of `run_id` values in the request body. The system will process all your completed tasks and return URLs for each audio file, making it easy to download or reference them in your application.

## Understanding the Response

This endpoint returns a JSON response containing file URLs for each successfully processed run\_id. Each audio file URL in the response corresponds to a completed text-to-speech task, allowing you to efficiently handle multiple audio files without the overhead of individual requests.

The bulk response structure provides:

* **Organized Results:** Each `run_id` is mapped to its corresponding audio file URL.
* **Error Handling:** Clear indication of any failed or unavailable runs.
* **Efficient Processing:** Single request handles multiple audio files.

<Tip>This bulk endpoint is particularly useful for applications that generate multiple audio segments simultaneously, such as creating audiobook chapters, processing multiple language versions, or handling batch content generation.</Tip>

## Request Format

The request body should contain an array of `run_id` values for the completed text-to-speech tasks you want to retrieve:

```json theme={null}
{
  "run_ids": [12345, 12346, 12347, 12348]
}
```

### Response Structure

The response will be a JSON object containing URLs for each successfully processed audio file:

```json theme={null}
{
    "12345": "https://audio-storage.camb.ai/files/audio_12345.flac",
    "12346": "https://audio-storage.camb.ai/files/audio_12346.flac",
    "12347": "https://audio-storage.camb.ai/files/audio_12347.flac",
    "12348": "https://audio-storage.camb.ai/files/audio_12348.flac"
}
```

<Note>File URLs have an expiration time, so download or use them promptly rather than storing them long-term. Plan to process your audio files within a reasonable timeframe after retrieval.</Note>

## Examples

### Retrieving Multiple Audio Files

Here's how to retrieve multiple generated audio files using Python:

```python [expandable] theme={null}
import requests

# Your API authentication
headers = {
    "x-api-key": "your-api-key",  # Replace with your actual API key
    "Content-Type": "application/json",
}

# List of run_ids from your completed TTS tasks (must be between 2-5 run_ids)
run_ids = [12345, 12346, 12347, 12348]  # Replace with your actual run_ids


def get_bulk_audio_results(run_ids):
    """
    Retrieves URLs for multiple completed TTS tasks in a single request.

    Args:
        run_ids: List of run_id values for completed TTS tasks (must be 2-5 items)

    Returns:
        dict: Dictionary mapping run_ids to their audio file URLs
    """
    # Validate the number of run_ids
    if len(run_ids) < 2 or len(run_ids) > 5:
        print(
            f"Error: Must provide between 2 and 5 run_ids. You provided {len(run_ids)}."
        )
        return {}

    print(f"Retrieving audio URLs for {len(run_ids)} completed tasks...")

    # Prepare the request payload
    payload = {"run_ids": run_ids}

    try:
        # Make the POST request
        response = requests.post(
            "https://client.camb.ai/apis/tts-results",
            headers=headers,
            json=payload,
        )

        # Check if the request was successful
        response.raise_for_status()

        # Parse the response
        results = response.json()

        print(f"Successfully retrieved {len(results)} audio file URLs!")
        return results

    except requests.exceptions.RequestException as e:
        print(f"Error retrieving bulk audio results: {e}")
        return {}


# Retrieve all audio URLs
audio_urls = get_bulk_audio_results(run_ids)

# Process the results
for run_id, output_json in audio_urls.items():
    print(f"Run ID {run_id}: {output_json.get('output_url')}")
```

## Best Practices

### Request Size Requirements

This endpoint requires a specific batch size for optimal performance and resource management:

* **Minimum**: You must provide at least 2 `run_id` values per request
* **Maximum**: You can provide up to 5 `run_id` values per request
* **Validation**: Requests outside this range will be rejected with a validation error

### Handling Larger Datasets

If you have more than 5 completed TTS tasks to retrieve:

* **Split into Multiple Requests**: Divide your `run_id` list into chunks of 2-5 items
* **Sequential Processing**: Process chunks sequentially to avoid rate limiting
* **Batch Management**: Implement logic to group your run\_ids efficiently

## Next Steps

With your bulk audio retrieval capabilities in place, you can:

1. **Build Efficient Workflows**: Process multiple audio files simultaneously in your applications
2. **Create Batch Processing Systems**: Handle large-scale content generation with minimal API overhead
3. **Implement Robust Error Handling**: Ensure your application gracefully handles partial failures
4. **Optimize Resource Usage**: Reduce API calls and improve application performance

This bulk endpoint provides the foundation for scalable voice applications that can handle multiple audio files efficiently and reliably.


## OpenAPI

````yaml post /tts-results
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers:
  - url: https://client.camb.ai/apis
security: []
paths:
  /tts-results:
    post:
      tags:
        - APIs
        - Text-to-Speech
      summary: Fetch Text-to-Speech Results
      operationId: get_tts_results_tts_results_post
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RunIDsRequestPayload'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BulkTTSRunsResults'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - APIKeyHeader: []
components:
  schemas:
    RunIDsRequestPayload:
      properties:
        run_ids:
          items:
            type: integer
            exclusiveMinimum: 0
          type: array
          maxItems: 5
          minItems: 2
          uniqueItems: true
          title: Run IDs
          description: >-
            An array of unique positive integers, each representing the ID of a
            specific run. You must provide between 2 and 5 IDs, and all IDs must
            correspond to the same run type (e.g., all text-to-speech or all
            dubbing runs).
          example:
            - 12345
            - 6789
      type: object
      required:
        - run_ids
      title: RunIDsRequestPayload
    BulkTTSRunsResults:
      type: object
      title: BulkTTSRunsResults
      additionalProperties:
        $ref: '#/components/schemas/AudioOutputFileURLResponse'
      minProperties: 1
      maxProperties: 5
      description: >-
        An object containing the results of one to five text-to-speech (TTS)
        runs. Each key in the object is a unique identifier for a run, and the
        corresponding value is the Text-to-Speech run details.
      example:
        '1234':
          output_url: https://audio-storage.camb.ai/files/audio_1234.flac
        '5678':
          output_url: https://audio-storage.camb.ai/files/audio_5678.flac
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    AudioOutputFileURLResponse:
      type: object
      properties:
        output_url:
          title: Output URL
          type: string
          description: A presigned URL that points to the output audio file.
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
  securitySchemes:
    APIKeyHeader:
      type: apiKey
      in: header
      name: x-api-key
      description: >-
        The `x-api-key` is a custom header required for authenticating requests
        to our API. Include this header in your request with the appropriate API
        key value to securely access our endpoints. You can find your API key(s)
        in the 'API' section of our studio website.

````