Skip to main content

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.
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.

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
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.

Preload Endpoint

Endpoint Details

PropertyValue
MethodPOST
URLhttps://api.tryhamsa.com/v2/tts/voices/custom/preload
AuthenticationAPI Key (Token)
Content-Typeapplication/json

Request Body

{
  "voiceId": "your-custom-voice-id"
}
ParameterTypeRequiredDescription
voiceIdstringYesThe unique identifier of your custom cloned voice

Response

Success Response (200):
{
  "success": true,
  "message": "Custom voice have been preloaded successfully",
  "data": []
}
Error Responses:
StatusDescription
400Bad request - Invalid voice ID format
401Unauthorized - Invalid or missing API key
404Voice not found - The specified voice ID doesn’t exist
500Server error - Internal server error

Code Examples

JavaScript/Node.js

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

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

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:
// 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:
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]}`);
    }
  });
}

Best Practices

Preload Early

Call the preload endpoint as early as possible in your application lifecycle

Handle Failures Gracefully

If preloading fails, log a warning but don’t block your app. The voice will load on first use with added latency

Preload Once

You only need to preload each voice once. Don’t call the endpoint repeatedly for the same voice

Use Environment Variables

Store your API key and voice IDs in environment variables, not in code

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