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

# Create Translated Text-to-Speech

> Creates a task to translate input text and generate corresponding speech audio

Transform written content across language barriers with our powerful translated text-to-speech system. This innovative endpoint enables you to seamlessly convert text from one language into spoken audio in another language in a single streamlined process. Whether you're creating multilingual content, developing educational materials, building accessible applications, or expanding your global reach, this capability allows you to quickly generate localized audio content while maintaining natural pronunciation and intonation specific to the target language.

<Note>
  Once the task is complete, the outputs can be retrieved using these endpoints:

  * [`/translation-result/{run_id}`](get-translation-run-result): Returns the translated text.
  * [`/tts-result/{run_id}`](get-tts-result): Returns the generated voiceover audio
</Note>

## How It Works

When you submit a request to this endpoint, our system processes your input text through a streamlined workflow:

* First, the system creates a dedicated task and returns a unique `task_id` for tracking.
* Your source text is then accurately translated to the target language using advanced neural machine translation models that preserve meaning andn context.
* Finally, the translated text is converted into natural-sounding speech using language-specific voice models that capture the appropriate pronunciation and intonation of the target language.
* You can monitor the status of your request by polling the [`/translated-tts/{task_id}`](poll-translated-tts-result) endpoint until processing is complete.

## Creating Your First Translated Text-to-Speech Request

Let's examine how to initiate a translated text-to-speech task using Python:

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

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

def create_translated_tts(text, source_language, target_language, voice_id=None):
    """
    Submits a new translated text-to-speech task and returns the task ID for tracking.

    Parameters:
    - text: The source text to be translated and converted to speech
    - source_language: Language id of the input text (e.g., 1 for English)
    - target_language: Language id for the desired output translation and speech (e.g., 54 for Spanish)
    - voice_id: Optional specific voice to use for the target language
    """
    try:
        # Prepare the request body
        payload = {
            "text": text,
            "source_language": source_language,
            "target_language": target_language
        }

        # Add voice_id if specified
        if voice_id:
            payload["voice_id"] = voice_id

        # Submit the request
        response = requests.post(
            "https://client.camb.ai/apis/translated-tts",
            headers=headers,
            data=json.dumps(payload)
        )

        # Verify the request was successful
        response.raise_for_status()

        # Extract the task ID from the response
        result = response.json()
        task_id = result.get("task_id")
        run_id = result.get("run_id")

        print(f"Translated TTS task submitted successfully! Task ID: {task_id}")
        print(f"Run ID for retrieving results: {run_id}")
        return task_id, run_id

    except requests.exceptions.RequestException as e:
        print(f"Error submitting translated TTS task: {e}")
        if hasattr(e, 'response') and e.response is not None:
            print(f"Response content: {e.response.text}")
        return None, None

# Example usage
source_text = "Welcome to our global product demonstration. We're excited to share these new features with you."
task_id, run_id = create_translated_tts(
    text=source_text,
    source_language=1, # Language ID (e.g., `1` for English - United States)
    target_language=88  # Language ID (e.g., `88` for Japanese - Japan)
)
```

## Monitoring Your Translation and Speech Generation Progress

After submission, your task enters our processing pipeline. You can monitor the progress by polling the status endpoint:

```python [expandable] theme={null}
def check_translated_tts_status(task_id):
    """
    Checks the status of a translated text-to-speech task.
    Returns the current status and any available result information.

    Parameters:
    - task_id: The ID of the task to check
    """
    if not task_id:
        print("No task ID provided.")
        return None

    try:
        response = requests.get(
            f"https://client.camb.ai/apis/translated-tts/{task_id}",
            headers=headers
        )

        # Verify the request was successful
        response.raise_for_status()

        # Parse the status information
        status_data = response.json()
        print(f"Current status: {status_data['status']}")

        # If the task is complete, show how to access results
        if status_data['status'] == "SUCCESS":
            print("Translation and speech generation completed successfully!")
            print(f"Use the run_id to retrieve your results.")
            print(f"- Translation: GET /translation-result/{status_data.get('run_id')}")
            print(f"- Audio: GET /tts-result/{status_data.get('run_id')}")

        return status_data

    except requests.exceptions.RequestException as e:
        print(f"Error checking task status: {e}")
        return None

# Check the status of your task
status_info = check_translated_tts_status(task_id)
```

## Retrieving Your Results

Once your task is complete, you can retrieve both the translated text and the generated audio using the provided run\_id:

```python [expandable] theme={null}
def get_translation_result(run_id):
    """
    Retrieves the translated text result.

    Parameters:
    - run_id: The run ID returned from the initial request
    """
    try:
        response = requests.get(
            f"https://client.camb.ai/apis/translation-result/{run_id}",
            headers=headers
        )

        response.raise_for_status()
        result = response.json()

        print(f"Translation successful!")
        print(f"Translated text: {result.get('translated_text')}")
        return result

    except requests.exceptions.RequestException as e:
        print(f"Error retrieving translation: {e}")
        return None

def get_tts_result(run_id):
    """
    Retrieves the generated audio file.

    Parameters:
    - run_id: The run ID returned from the initial request
    """
    try:
        response = requests.get(
            f"https://client.camb.ai/apis/tts-result/{run_id}",
            headers=headers
        )

        response.raise_for_status()
        result = response.json()

        print(f"Audio retrieval successful!")
        print(f"Audio URL: {result.get('audio_url')}")
        return result

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

# Retrieve your results
translation = get_translation_result(run_id)
audio = get_tts_result(run_id)
```

## Best Practices for Translated Text-to-Speech

To achieve the highest quality results for your multilingual audio content:

1. **Provide Clear Source Text**: Ensure your source text is free of grammatical errors, unusual abbreviations, or ambiguous phrases to improve translation accuracy.

2. **Consider Cultural Context**: Be mindful of cultural references that may not translate effectively across languages, and adapt your content accordingly.

3. **Use Appropriate Sentence Length**: For optimal speech generation, break long, complex sentences into shorter ones, especially for languages that differ structurally from the source.

## Supported Languages & Voices

Our system supports a wide range of language pairs for translation and speech synthesis. The quality and naturalness of speech may vary depending on the specific language combinations. Checkout the [`/target-languages`](get-target-languages) endpoint for a list of supported languages and [`/list-voices`](list-voices) endpoint for a list of available voices which includes public voices and your own custom voices.


## OpenAPI

````yaml post /translated-tts
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers:
  - url: https://client.camb.ai/apis
security: []
paths:
  /translated-tts:
    post:
      tags:
        - Apis
      summary: Create Translated Tts
      operationId: translated-tts_translated-tts_post
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateTranslatedTTSRequestPayload'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - APIKeyHeader: []
components:
  schemas:
    CreateTranslatedTTSRequestPayload:
      allOf:
        - $ref: '#/components/schemas/CreateTaskWithNameAndDescription'
        - properties:
            text:
              type: string
              title: Text
              description: >-
                The input text content that you want to translate and convert to
                speech. Provide clear, well-structured text for optimal results.
            voice_id:
              type: integer
              title: Voice Id
              description: >-
                A unique identifier for the specific voice to use for speech
                synthesis in the target language. Each voice has distinct
                characteristics including tone, accent, and speaking style.
              default: 147320
            age:
              anyOf:
                - type: integer
                - type: 'null'
              title: Age
              default: 28
              description: >-
                The simulated age of the speaker in years, which influences
                voice characteristics. Defaults to `28` if not specified. Set to
                null to use the default voice age.
            formality:
              anyOf:
                - $ref: '#/components/schemas/Formalities'
                - type: 'null'
              default: 2
              description: >-
                The level of formality to use for the translation. Values range
                from casual (`1`), with a default of `2` (formal). This affects
                the translation's tone and word choice based on cultural norms
                of the target language.
            gender:
              anyOf:
                - $ref: '#/components/schemas/Gender'
                - type: 'null'
              default: 1
              description: >-
                The gender of the synthesized voice. Influences voice
                characteristics based on typical speech patterns. Defaults to
                `1` (typically representing male).
            source_language:
              $ref: '#/components/schemas/SourceLanguages'
              description: >-
                The language code of the input text (e.g., `1` for English, `54`
                for Spanish). Must match one of the supported language codes.
            target_language:
              $ref: '#/components/schemas/Languages'
              example: 81
              description: >-
                The language code for the desired output translation and speech
                (e.g., `76` for French, `88` for Japanese). This the language of
                translation.
            chosen_dictionaries:
              $ref: '#/components/schemas/ChosenDictionariesSchema'
          type: object
          required:
            - text
            - voice_id
            - source_language
            - target_language
      title: CreateTranslatedTTSRequestPayload
      description: >-
        Parameters for initiating a translation and text-to-speech task,
        including source text, language preferences, and voice characteristics.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    CreateTaskWithNameAndDescription:
      properties:
        project_name:
          type: string
          title: Project Name
          description: >-
            Enter a distinctive name for your project that reflects its purpose
            or content. This name will be displayed in your CAMB.AI workspace
            dashboard and used to organize related assets, transcriptions, etc..
            . Choose something memorable that helps you quickly identify this
            specific project among your other voice, audio and localization
            tasks.
          minLength: 3
          maxLength: 255
          nullable: true
        project_description:
          type: string
          title: Project Description
          description: >-
            Provide details about your project's goals and specifications.
            Include information such as the target languages for translation or
            dubbing, desired voice characteristics, emotional tones to capture,
            or specific audio processing requirements, outlining the workflow
            here can serve as valuable documentation for organizational
            purposes.
          minLength: 3
          maxLength: 5000
          nullable: true
    Formalities:
      type: integer
      enum:
        - 1
        - 2
      title: Formalities
    Gender:
      type: integer
      enum:
        - 0
        - 1
        - 2
        - 9
      title: Gender
      description: The gender of the speaker.
    SourceLanguages:
      type: integer
      enum:
        - 1
        - 2
        - 3
        - 4
        - 5
        - 6
        - 7
        - 8
        - 9
        - 10
        - 11
        - 12
        - 13
        - 14
        - 15
        - 16
        - 17
        - 18
        - 19
        - 20
        - 21
        - 22
        - 23
        - 24
        - 25
        - 26
        - 27
        - 28
        - 29
        - 30
        - 31
        - 32
        - 33
        - 34
        - 35
        - 36
        - 37
        - 38
        - 39
        - 40
        - 41
        - 42
        - 43
        - 44
        - 45
        - 46
        - 47
        - 48
        - 49
        - 50
        - 51
        - 52
        - 53
        - 54
        - 55
        - 56
        - 57
        - 58
        - 59
        - 60
        - 61
        - 62
        - 63
        - 64
        - 65
        - 66
        - 67
        - 68
        - 69
        - 70
        - 71
        - 73
        - 74
        - 75
        - 76
        - 78
        - 79
        - 80
        - 81
        - 82
        - 83
        - 84
        - 85
        - 86
        - 87
        - 88
        - 90
        - 91
        - 92
        - 93
        - 94
        - 95
        - 96
        - 97
        - 98
        - 99
        - 100
        - 101
        - 102
        - 103
        - 104
        - 106
        - 107
        - 108
        - 109
        - 110
        - 111
        - 112
        - 113
        - 114
        - 115
        - 116
        - 117
        - 118
        - 119
        - 120
        - 121
        - 122
        - 123
        - 124
        - 125
        - 126
        - 127
        - 128
        - 129
        - 130
        - 131
        - 132
        - 133
        - 134
        - 135
        - 136
        - 139
        - 140
        - 141
        - 142
        - 143
        - 144
        - 145
        - 146
        - 148
      default: 1
    Languages:
      type: integer
      enum:
        - 1
        - 2
        - 3
        - 4
        - 5
        - 6
        - 7
        - 8
        - 9
        - 10
        - 11
        - 12
        - 13
        - 14
        - 15
        - 16
        - 17
        - 18
        - 19
        - 20
        - 21
        - 22
        - 23
        - 24
        - 25
        - 26
        - 27
        - 28
        - 29
        - 30
        - 31
        - 32
        - 33
        - 34
        - 35
        - 36
        - 37
        - 38
        - 39
        - 40
        - 41
        - 42
        - 43
        - 44
        - 45
        - 46
        - 47
        - 48
        - 49
        - 50
        - 51
        - 52
        - 53
        - 54
        - 55
        - 56
        - 57
        - 58
        - 59
        - 60
        - 61
        - 62
        - 63
        - 64
        - 65
        - 66
        - 67
        - 68
        - 69
        - 70
        - 71
        - 72
        - 73
        - 74
        - 75
        - 76
        - 77
        - 78
        - 79
        - 80
        - 81
        - 82
        - 83
        - 84
        - 85
        - 86
        - 87
        - 88
        - 89
        - 90
        - 91
        - 92
        - 93
        - 94
        - 95
        - 96
        - 97
        - 98
        - 99
        - 100
        - 101
        - 102
        - 103
        - 104
        - 105
        - 106
        - 107
        - 108
        - 109
        - 110
        - 111
        - 112
        - 113
        - 114
        - 115
        - 116
        - 117
        - 118
        - 119
        - 120
        - 121
        - 122
        - 123
        - 124
        - 125
        - 126
        - 127
        - 128
        - 129
        - 130
        - 131
        - 132
        - 133
        - 134
        - 135
        - 136
        - 139
        - 140
        - 141
        - 142
        - 143
        - 144
        - 145
        - 146
        - 147
        - 148
        - 149
        - 150
      title: Languages
      default: 1
    ChosenDictionariesSchema:
      type: array
      nullable: true
      items:
        type: integer
      uniqueItems: true
      minItems: 1
      default: null
      description: >-
        An optional list of dictionary IDs selected by the user. Each entry must
        be an integer corresponding to a valid dictionary ID. If provided, at
        least one ID is required.
    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.

````