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

# Using Custom Cloned Voices

> Learn how to preload and use your custom cloned voices with Hamsa Real-Time APIs

## Overview

When you create a custom cloned voice in Hamsa, you need to preload it into the system before using it with any real-time API endpoints. This one-time preload ensures your custom voice is ready and available, eliminating latency when making real-time TTS requests or WebSocket connections.

<Info>
  **Why Preloading Matters:**
  Custom cloned voices require initialization in the system before they can be used. Without preloading, the first real-time request using your custom voice would experience significant latency as the system loads the voice model.
</Info>

***

## When to Preload

You should call the preload endpoint:

* **Once when your application starts** - Preload during your app's initialization phase
* **Before any real-time TTS or WebSocket usage** - Ensure the voice is ready before making real-time requests
* **Only once per voice** - You don't need to preload the same voice multiple times

<Note>
  **When is Preloading Required?**

  This preload step is required when using your custom cloned voice with:

  * Real-Time TTS REST API (`/v1/realtime/tts`)
  * Streaming TTS REST API (`/v1/realtime/tts-stream`)
  * Real-Time WebSocket connections

  **Not required for Voice Agents SDK** - The SDK handles voice preloading automatically.
</Note>

***

## Preload Endpoint

### Endpoint Details

| Property           | Value                                                   |
| ------------------ | ------------------------------------------------------- |
| **Method**         | `POST`                                                  |
| **URL**            | `https://api.tryhamsa.com/v2/tts/voices/custom/preload` |
| **Authentication** | API Key (Token)                                         |
| **Content-Type**   | `application/json`                                      |

### Request Body

```json theme={null}
{
  "voiceId": "your-custom-voice-id"
}
```

| Parameter | Type   | Required | Description                                       |
| --------- | ------ | -------- | ------------------------------------------------- |
| `voiceId` | string | Yes      | The unique identifier of your custom cloned voice |

### Response

**Success Response (200):**

```json theme={null}
{
  "success": true,
  "message": "Custom voice have been preloaded successfully",
  "data": []
}
```

**Error Responses:**

| Status | Description                                            |
| ------ | ------------------------------------------------------ |
| `400`  | Bad request - Invalid voice ID format                  |
| `401`  | Unauthorized - Invalid or missing API key              |
| `404`  | Voice not found - The specified voice ID doesn't exist |
| `500`  | Server error - Internal server error                   |

***

## Code Examples

### JavaScript/Node.js

```javascript theme={null}
async function preloadCustomVoice(voiceId) {
  const response = await fetch('https://api.tryhamsa.com/v2/tts/voices/custom/preload', {
    method: 'POST',
    headers: {
      'Authorization': 'Token YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      voiceId: voiceId
    })
  });

  const data = await response.json();

  if (!response.ok) {
    throw new Error(`Failed to preload voice: ${data.message || response.statusText}`);
  }

  return data;
}

// Call this when your application starts
async function initializeApp() {
  try {
    await preloadCustomVoice('c803658e-ccec-47e7-ad0f-1caf9ba4babb');
    console.log('Custom voice preloaded successfully');

    // Now you can safely use real-time TTS with this voice
  } catch (error) {
    console.error('Failed to preload voice:', error);
  }
}

initializeApp();
```

### Python

```python theme={null}
import requests

def preload_custom_voice(voice_id: str, api_key: str) -> dict:
    """Preload a custom cloned voice into the system."""
    response = requests.post(
        'https://api.tryhamsa.com/v2/tts/voices/custom/preload',
        headers={
            'Authorization': f'Token {api_key}',
            'Content-Type': 'application/json'
        },
        json={
            'voiceId': voice_id
        }
    )

    response.raise_for_status()
    return response.json()


# Call this when your application starts
def initialize_app():
    api_key = 'YOUR_API_KEY'
    voice_id = 'c803658e-ccec-47e7-ad0f-1caf9ba4babb'

    try:
        result = preload_custom_voice(voice_id, api_key)
        print('Custom voice preloaded successfully')

        # Now you can safely use real-time TTS with this voice
    except requests.exceptions.HTTPError as error:
        print(f'Failed to preload voice: {error}')


if __name__ == '__main__':
    initialize_app()
```

### cURL

```bash theme={null}
curl -X POST https://api.tryhamsa.com/v2/tts/voices/custom/preload \
  -H "Authorization: Token YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "voiceId": "c803658e-ccec-47e7-ad0f-1caf9ba4babb"
  }'
```

***

## Integration Patterns

### App Startup Pattern

The recommended approach is to preload your custom voice during application initialization, before making any real-time API calls:

```javascript theme={null}
// app.js or index.js
const CUSTOM_VOICE_ID = 'your-custom-voice-id';
const API_KEY = process.env.HAMSA_API_KEY;

async function preloadVoice() {
  const response = await fetch('https://api.tryhamsa.com/v2/tts/voices/custom/preload', {
    method: 'POST',
    headers: {
      'Authorization': `Token ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ voiceId: CUSTOM_VOICE_ID })
  });

  if (!response.ok) {
    console.warn('Voice preload failed, real-time TTS may have initial latency');
  }
}

async function startApp() {
  // Preload custom voice at app startup
  await preloadVoice();

  // Now you can use the custom voice with real-time TTS APIs
  // without experiencing initial latency
}

startApp();
```

### Multiple Voices Pattern

If you have multiple custom voices, preload them all during startup:

```javascript theme={null}
const CUSTOM_VOICES = [
  'voice-id-1',
  'voice-id-2',
  'voice-id-3'
];

async function preloadAllVoices() {
  const preloadPromises = CUSTOM_VOICES.map(voiceId =>
    fetch('https://api.tryhamsa.com/v2/tts/voices/custom/preload', {
      method: 'POST',
      headers: {
        'Authorization': `Token ${API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ voiceId })
    })
  );

  const results = await Promise.allSettled(preloadPromises);

  results.forEach((result, index) => {
    if (result.status === 'fulfilled' && result.value.ok) {
      console.log(`Voice ${CUSTOM_VOICES[index]} preloaded`);
    } else {
      console.warn(`Failed to preload voice ${CUSTOM_VOICES[index]}`);
    }
  });
}
```

***

## Troubleshooting

### Voice Not Found (404)

If you receive a 404 error:

* Verify the voice ID is correct
* Ensure the custom voice was created successfully in your account
* Check that you're using the correct API key associated with the voice

### Unauthorized (401)

If you receive a 401 error:

* Verify your API key is valid
* Ensure the API key has permissions to access custom voices
* Check the Authorization header format: `Token YOUR_API_KEY`

### Latency Still Present

If you notice latency even after preloading:

* Ensure the preload completed successfully before making real-time requests
* Check that you're using the same voice ID in both preload and TTS requests
* Verify the preload was called in the current session

***

## Related Resources

<CardGroup cols={2}>
  <Card title="Real-Time TTS" href="/api-reference/endpoint/rt-generate-stt" icon="volume-high">
    Use your preloaded voice with the TTS endpoint
  </Card>

  <Card title="Streaming TTS" href="/api-reference/endpoint/rt-generate-tts-stream" icon="wave-square">
    Stream audio output with your custom voice
  </Card>

  <Card title="Real-Time WebSocket" href="/websocket/websocket-tts#using-custom-cloned-voices" icon="plug">
    Use custom voices with WebSocket connections
  </Card>
</CardGroup>
