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

# Transcription

> Transcribe an audio or video file into timestamped text using the Python or TypeScript SDK

## Overview

Convert spoken audio or video into accurate, timestamped text with speaker labels. The pipeline is asynchronous: submit a job with a local file or a public URL, poll until it completes, then retrieve the segmented transcript.

### Prerequisites

**1. Create an account**

Sign up at [CAMB.AI Studio](https://studio.camb.ai) if you haven't already.

**2. Get your API key**

Go to **Settings → API Keys** in Studio and copy your key. See [Authentication](https://docs.camb.ai/getting-started/authentication.md) for details.

**3. Install the SDK**

```bash Python theme={null}
pip install camb-sdk
```

```bash TypeScript theme={null}
npm install @camb-ai/sdk
```

Skip this step if you're using the [direct API](https://docs.camb.ai/tutorials/direct-api.md).

**4. Set your API key to use in your code**

```bash theme={null}
export CAMB_API_KEY="your_api_key_here"
```

***

## Transcription mode and audio preparation

| Field | Default | Behavior |
| - | - | - |
| `transcription_mode` | `"fast"` | Use `"slow"` for a slower mode that may improve accuracy. Both modes include speaker diarization. |
| `run_audio_cleaning` | `true` | Runs source separation. Set `false` for clean speech; media extraction/decoding still runs. This does not disable diarization. |
| `include_music_in_fg` | `true` | Keeps music in the foreground during separation. Set `false` to remove it. Has no effect when cleaning is disabled. |
| `language` | Required | Source locale, numeric language ID, or `"auto"` for detection (`"ax-ax"` and `321` also select auto). |
| `formatting_options` | Omitted | Optional subtitle segmentation rules. Use a Python options object/dict with the SDK, or a JSON-encoded string in multipart HTTP requests. |

These options can be combined. For example, slow transcription can run with cleaning
disabled. Changing the mode requires submitting a new job.

```python theme={null}
from camb.client import CambAI

client = CambAI()  # Reads CAMB_API_KEY.
job = client.transcription.create_transcription(
    media_url="https://example.com/meeting.mp3",
    language="auto",
    transcription_mode="slow",  # Change to "fast" for the default mode.
    run_audio_cleaning=False,   # This example assumes clean speech.
    include_music_in_fg=True,  # Ignored while cleaning is disabled.
    formatting_options={
        "max_segment_duration_in_seconds": 6,
        "max_characters_in_segment": 42,
    },
)
print(job.task_id)
```

For an executable Python example with editable options, polling, and error handling,
see [transcription.py](https://github.com/Camb-ai/cambai-python-sdk/blob/to-main/transcription-audio-cleaning-auto/examples/transcription.py).

## Code

```python Python theme={null}
import os
import time
from camb.client import CambAI
from camb.types.language_enums import Languages

client = CambAI(api_key=os.getenv("CAMB_API_KEY"))

def transcribe_audio():
    # Step 1: Submit the transcription job
    response = client.transcription.create_transcription(
        language=Languages.EN_US,  # English (US)
        media_url="https://example.com/meeting.mp3",
        transcription_mode="fast",  # Or "slow".
        run_audio_cleaning=True,
        include_music_in_fg=True,
    )

    task_id = response.task_id
    print(f"Transcription task created: {task_id}")

    # Step 2: Poll until complete
    while True:
        status = client.transcription.get_transcription_task_status(task_id=task_id)
        print(f"Status: {status.status}")

        if status.status == "SUCCESS":
            # Step 3: Retrieve the transcript
            result = client.transcription.get_transcription_result(run_id=status.run_id)
            for segment in result.transcript[:3]:
                print(f"[{segment.start:.2f}-{segment.end:.2f}] {segment.speaker}: {segment.text}")
            break
        elif status.status == "ERROR":
            print(f"Transcription failed: {status.exception_reason}")
            break

        time.sleep(5)

transcribe_audio()
```

```javascript TypeScript theme={null}
import { CambClient, CambApi } from '@camb-ai/sdk';

const client = new CambClient({
    apiKey: process.env.CAMB_API_KEY
});

async function transcribeAudio() {
    // Step 1: Submit the transcription job
    const response = await client.transcription.createTranscription({
        language: CambApi.Languages.EN_US, // English (US)
        media_url: 'https://example.com/meeting.mp3',
        transcription_mode: 'fast', // Or 'slow'.
        run_audio_cleaning: true,
        include_music_in_fg: true
    });

    const taskId = response.task_id;
    console.log(`Transcription task created: ${taskId}`);

    // Step 2: Poll until complete
    while (true) {
        const status = await client.transcription.getTranscriptionTaskStatus({
            task_id: taskId
        });

        console.log(`Status: ${status.status}`);

        if (status.status === 'SUCCESS') {
            // Step 3: Retrieve the transcript
            const result = await client.transcription.getTranscriptionResult({
                run_id: status.run_id
            });

            for (const segment of result.transcript.slice(0, 3)) {
                console.log(
                    `[${segment.start.toFixed(2)}-${segment.end.toFixed(2)}] ${segment.speaker}: ${segment.text}`
                );
            }
            break;
        } else if (status.status === 'ERROR') {
            console.error(`Transcription failed: ${status.exception_reason}`);
            break;
        }

        await new Promise(resolve => setTimeout(resolve, 5000));
    }
}

transcribeAudio();
```

### Transcribing a local file

Pass `media_file` instead of `media_url` to upload a local file:

```python Python theme={null}
with open("meeting.mp3", "rb") as audio_file:
    response = client.transcription.create_transcription(
        language=Languages.EN_US,
        media_file=audio_file
    )
```

```javascript TypeScript theme={null}
import { createReadStream } from 'fs';

const response = await client.transcription.createTranscription({
    language: CambApi.Languages.EN_US,
    media_file: createReadStream('meeting.mp3')
});
```

***

## Subtitle Formatting

By default, the transcript is segmented by natural speech patterns rather than by subtitle-length rules. Pass `formatting_options` to segment it into subtitle-ready cues instead:

```python Python theme={null}
from camb.types.subtitle_formatting_options import SubtitleFormattingOptions

formatting_options = SubtitleFormattingOptions(
    max_segment_duration_in_seconds=6,
    max_characters_in_segment=42,
)

response = client.transcription.create_transcription(
    language=Languages.EN_US,
    media_url="https://example.com/meeting.mp3",
    formatting_options=formatting_options,
)
```

```javascript TypeScript theme={null}
const response = await client.transcription.createTranscription({
    language: CambApi.Languages.EN_US,
    media_url: 'https://example.com/meeting.mp3',
    formatting_options: {
        max_segment_duration_in_seconds: 7, // Default: 7 seconds; caps each segment length.
        min_segment_duration_in_seconds: 1, // Default: 1 second; avoids very short segments when possible.
        max_characters_in_segment: 42, // Default: 42 characters; keeps subtitle-style lines readable.
    }
});
```

* **`max_segment_duration_in_seconds`** (default `7.0`): the longest a single segment may stay on screen.
* **`min_segment_duration_in_seconds`** (default `1.0`): the shortest a single segment may stay on screen.
* **`max_characters_in_segment`** (default `42`): the maximum number of characters allowed in one segment.

Once the task succeeds, request the transcript as `srt` or `vtt` instead of the structured JSON by passing `format_type` (and optionally `data_type`) to the result call. The response then carries a single `transcript` string instead of a segment array:

```python Python theme={null}
result = client.transcription.get_transcription_result(
    status.run_id,
    format_type="srt",
    data_type="raw_data",
)
print(result.transcript)
```

```javascript TypeScript theme={null}
const result = await client.transcription.getTranscriptionResult({
    run_id: status.run_id,
    format_type: CambApi.TranscriptFileFormat.Srt,
    data_type: CambApi.TranscriptDataType.RawData
});
console.log(result.transcript);
```

> [!NOTE]
>
> Need subtitles translated into languages other than the source? Use the [Subtitles](https://docs.camb.ai/tutorials/subtitles-with-sdk.md) tutorial. It runs the same segmentation across one or more target languages.

***

## Parameters

### Required

| Parameter | Type | Description |
| - | - | - |
| `language` | `Languages` enum | Source language for the spoken content (e.g. `Languages.EN_US`). The raw API also accepts locale-tag strings like `"en-us"`; numeric IDs still work but are deprecated. See [Languages](#languages). |
| `media_file` *or* `media_url` | file *or* string | Provide exactly one — a local audio/video file, or a publicly accessible URL. |

### Optional

| Parameter | Type | Description |
| - | - | - |
| `project_name` | string | Label for the job in your dashboard |
| `project_description` | string | Additional notes for the job |
| `folder_id` | integer | Place the run inside a specific folder |
| `transcription_mode` | `fast` or `slow` | Choose a faster transcript or a more thorough pass; defaults to `fast` |
| `formatting_options` | `SubtitleFormattingOptions` object or dict | Segments the transcript into subtitle-ready cues instead of natural speech boundaries. See [Subtitle Formatting](#subtitle-formatting). |

### Result shape

`get_transcription_result` returns a `TranscriptionResult` with a `transcript` array. Each segment contains:

| Field | Type | Description |
| - | - | - |
| `start` | float | Segment start time in seconds |
| `end` | float | Segment end time in seconds |
| `text` | string | Transcribed text for the segment |
| `speaker` | string | Speaker label (e.g. `Speaker 1`) |

When you pass `format_type` and/or `data_type`, the call instead returns a `TranscriptExportResult` with a single `transcript` string, either the rendered `srt`/`vtt`/`txt` content or a presigned URL to it.

***

## Languages

The Python and TypeScript SDKs expect the `Languages` enum:

| Language | Enum | Locale (raw API) |
| - | - | - |
| English (US) | `Languages.EN_US` | `en-us` |
| Spanish (Spain) | `Languages.ES_ES` | `es-es` |
| French (France) | `Languages.FR_FR` | `fr-fr` |
| German (Germany) | `Languages.DE_DE` | `de-de` |
| Mandarin Chinese | `Languages.ZH_CN` | `zh-cn` |
| Japanese (Japan) | `Languages.JA_JP` | `ja-jp` |
| Arabic | `Languages.AR_SA` | `ar-sa` |

If you're calling the API directly (not via the SDK), pass the locale tag. Numeric language IDs still work but are deprecated.

> [card]
>
> For the full list of supported source languages, see the Source Languages reference.
>
> [Open](https://docs.camb.ai/api-reference/endpoint/get-source-languages.md)

***

## Tips

* **Supported formats:** `.mp3`, `.wav`, `.aac`, `.flac`, `.mp4`, `.mov`, and `.mxf` (MXF is enterprise-only). For best quality use a lossless format like WAV or FLAC.
* **File size:** Uploaded files must be under 20 MB. For longer recordings, host the file and pass a `media_url` instead, or split the recording into chunks.
* **Polling timeout:** For long media, cap your polling loop (e.g. 60 attempts x 5s = 5 minutes) and handle the timeout gracefully.
* **Pick the right language:** Specifying the correct source language significantly improves accuracy. For multilingual content, choose the predominant language.

***

## Next Steps

> [card] [Create Transcription API](https://docs.camb.ai/api-reference/endpoint/create-transcription.md)
>
> Full API reference for the transcription endpoint.

> [card] [Poll Transcription Result](https://docs.camb.ai/api-reference/endpoint/poll-transcription-result.md)
>
> Status polling endpoint reference.

> [card] [Get Transcription Run Result](https://docs.camb.ai/api-reference/endpoint/get-transcription-run-result.md)
>
> Retrieve the transcript segments and timing data.

> [card] [Subtitles](https://docs.camb.ai/tutorials/subtitles-with-sdk.md)
>
> Generate cue-ready subtitles translated into one or more target languages.

> [card] [Dubbing](https://docs.camb.ai/tutorials/dubbing-with-sdk.md)
>
> Translate a video into another language while preserving the original voice.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.