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

# Transcribing a TikTok LIVE in Real Time

> Start a transcription session on a TikTok LIVE room and read what is said as it is said: over an event stream, by polling, or through a webhook.

## Overview

[`POST /tiktok/live/transcribe`](https://docs.vidnavigator.com/api-reference/endpoint/tiktok-live-transcribe.md) starts a **session** on a TikTok LIVE room. From then on, what is said in the room is transcribed as it is said: each sentence reaches you typically one to two seconds after it was spoken.

You need no TikTok account, no login and no browser, and there is nothing to install: the room is identified by its ID, its streamer or its URL.

> [!NOTE]
>
> **Availability:** every plan. How many rooms you can transcribe at the same time depends on your plan: see the [limits](https://docs.vidnavigator.com/api-reference/rate-limiting.md#tiktok-live-transcription).

## Prerequisites

- A VidNavigator API key.
- The [Python](https://docs.vidnavigator.com/sdks/python.md#live-transcription) or [JavaScript](https://docs.vidnavigator.com/sdks/javascript.md#live-transcription) SDK, version 3.5.0 or later, or any HTTP client.

## 1. Find a Room

A session needs a room that is **on air**. There are two ways to get one:

- **By keyword and country**: [TikTok LIVE Search](https://docs.vidnavigator.com/api-reference/endpoint/tiktok-live-search.md) returns the rooms broadcasting right now. Pass a room's `id` as `room_id`.
- **By streamer**: pass their `username`. To know first whether they are on air, [TikTok LIVE Room](https://docs.vidnavigator.com/api-reference/endpoint/tiktok-live-room.md) tells you (`status: "live"`), with the viewers and the chat.

Both are covered, with code, in [Searching TikTok](https://docs.vidnavigator.com/guides/tiktok-search.md#searching-tiktok-live-rooms).

## 2. Start a Session

Send exactly one of `room_id`, `username` or `url`.

```python Python
from vidnavigator import VidNavigatorClient

client = VidNavigatorClient()  # reads VIDNAVIGATOR_API_KEY

started = client.start_tiktok_live_transcription(
    username="creator",
    max_duration_minutes=120,
)
session_id = started.data.session.id
print(session_id, started.data.session.status)  # "starting", then "listening"
```

```javascript JavaScript
import { VidNavigatorClient } from 'vidnavigator';

const vn = new VidNavigatorClient({ apiKey: process.env.VIDNAVIGATOR_API_KEY });

const { session } = await vn.startTikTokLiveTranscription({
  username: 'creator',
  max_duration_minutes: 120,
});
const sessionId = session.id;
console.log(sessionId, session.status); // "starting", then "listening"
```

```bash cURL
curl -X POST "https://api.vidnavigator.com/v1/tiktok/live/transcribe" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"username": "creator", "max_duration_minutes": 120}'
```

Keep the session `id`: it reads, streams and stops the session.

| Option                 | What it does                                                                                                               |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `language`             | The language spoken (`en`, `fr`, `ar`...), when you know it. See [Languages](#languages).                                  |
| `max_duration_minutes` | The session stops by itself after that many minutes transcribed. Default 60, up to 1440 (24 hours).                        |
| `include_partials`     | Also receive the sentence being said, before it is final. See [Final and partial sentences](#final-and-partial-sentences). |
| `include_speakers`     | A label (`A`, `B`...) on each sentence. See [Speakers](#speakers).                                                         |
| `webhook_url`          | Have the sentences POSTed to your server. See [Webhook](#webhook).                                                         |

There is **one session per room** for your organization. Starting it a second time answers `200` with the session already running, so the call is safe to repeat.

## 3. Read the Transcript

| How                           | Best for                                                               |
| ----------------------------- | ---------------------------------------------------------------------- |
| [Event stream](#event-stream) | Each sentence as it is said. One connection carries all your sessions. |
| [Polling](#polling)           | Simple integrations, and catching up after an interruption.            |
| [Webhook](#webhook)           | Servers that prefer to be called.                                      |

They can be combined, and reading costs nothing.

### Event Stream

[`GET /tiktok/live/transcribe/events`](https://docs.vidnavigator.com/api-reference/endpoint/tiktok-live-transcribe-events.md) is a stream of Server-Sent Events that stays open. It sends a `started` event when a session starts listening, a `final` event for each sentence, and an `ended` event when the session is over.

```python Python
# Reconnects by itself, with the id of the last event received
for event in client.stream_tiktok_live_transcription_events(session_id=session_id):
    if event.event == "final":
        print(f"[{event.segment.start:.1f}s] {event.segment.text}")
    elif event.event == "ended":
        print("Session over:", event.data["status"], event.data["end_reason"])
        break
```

```javascript JavaScript
// Reconnects by itself, with the id of the last event received
for await (const event of vn.streamTikTokLiveTranscriptionEvents({ session_id: sessionId })) {
  if (event.event === 'final') {
    console.log(`[${event.data.start}s] ${event.data.text}`);
  } else if (event.event === 'ended') {
    console.log('Session over:', event.data.status, event.data.end_reason);
    break;
  }
}
```

```bash cURL
curl -N "https://api.vidnavigator.com/v1/tiktok/live/transcribe/events?session_id=SESSION_ID" \
  -H "X-API-Key: YOUR_API_KEY"
```

```text
id: 4821
event: final
data: {"session_id":"3f0c1c1e-7a52-4d0e-9a3b-0d2f8c1b7e55","seq":57,"start":103.29,"end":104.88,"text":"I'm from Gambia.","language":"en","timestamp":"2026-12-03T11:20:03.290Z"}
```

Leave `session_id` out to receive the events of **every** session of your organization on the same connection: each event carries its `session_id`.

**No sentence is lost when the connection is cut.** Every event except `partial` has an `id`. Reconnect with the last `id` you received, in the `Last-Event-ID` header or the `after` parameter, and the stream resumes with the event that followed. The server closes the connection from time to time: reconnecting is part of normal use. The SDKs do it for you. To resume after a restart of your own process, store the last `id` you handled and pass it as `after`.

> [accordion] A reconnect loop over plain HTTP
>
> ```python Python
> import json
> import time
>
> import requests
>
> URL = "https://api.vidnavigator.com/v1/tiktok/live/transcribe/events"
> HEADERS = {"X-API-Key": "YOUR_API_KEY"}
>
>
> def stream_events(session_id=None, last_id=None):
>     """Yield (event, data) for ever, reconnecting with the id of the last event received."""
>     params = {"session_id": session_id} if session_id else {}
>     while True:
>         headers = dict(HEADERS)
>         if last_id is not None:
>             headers["Last-Event-ID"] = str(last_id)
>         try:
>             with requests.get(URL, headers=headers, params=params, stream=True, timeout=(10, 60)) as resp:
>                 if resp.status_code < 500:
>                     resp.raise_for_status()  # 4xx: the request is wrong, retrying will not help
>                 if resp.ok:
>                     resp.encoding = "utf-8"
>                     fields = {}
>                     for line in resp.iter_lines(decode_unicode=True):
>                         if line == "":  # an empty line ends a block
>                             if "id" in fields:  # the first block has an id and no event: keep it too
>                                 last_id = int(fields["id"])
>                             if "data" in fields:
>                                 yield fields.get("event"), json.loads(fields["data"])
>                             fields = {}
>                         elif not line.startswith(":"):  # ":" starts a comment (keep-alive)
>                             name, _, value = line.partition(":")
>                             fields[name] = value.lstrip()
>         except (requests.ConnectionError, requests.Timeout, requests.exceptions.ChunkedEncodingError):
>             pass  # the connection was cut
>         time.sleep(3)  # then reconnect, with the last id
>
>
> for event, data in stream_events(session_id="SESSION_ID"):
>     if event == "final":
>         print(f'[{data["start"]:.1f}s] {data["text"]}')
>     elif event == "ended":
>         print("Session over:", data["status"], data["end_reason"])
>         break
> ```
>
> ```javascript JavaScript
> const EVENTS_URL = 'https://api.vidnavigator.com/v1/tiktok/live/transcribe/events';
> const HEADERS = { 'X-API-Key': 'YOUR_API_KEY' };
>
> // Yields { event, data } for ever, reconnecting with the id of the last event received.
> async function* streamEvents({ sessionId, lastId } = {}) {
>   const url = new URL(EVENTS_URL);
>   if (sessionId) url.searchParams.set('session_id', sessionId);
>   while (true) {
>     const headers = { ...HEADERS };
>     if (lastId != null) headers['Last-Event-ID'] = String(lastId);
>     let res;
>     try {
>       res = await fetch(url, { headers });
>     } catch {
>       res = null; // could not connect: try again
>     }
>     if (res && !res.ok && res.status < 500) throw new Error(`HTTP ${res.status}`); // 4xx: retrying will not help
>     if (res?.ok) {
>       try {
>         let buffer = '';
>         for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) {
>           buffer += chunk;
>           let end;
>           while ((end = buffer.indexOf('\n\n')) !== -1) { // an empty line ends a block
>             const fields = {};
>             for (const line of buffer.slice(0, end).split('\n')) {
>               if (line.startsWith(':')) continue; // a comment (keep-alive)
>               const colon = line.indexOf(':');
>               fields[line.slice(0, colon)] = line.slice(colon + 1).trimStart();
>             }
>             buffer = buffer.slice(end + 2);
>             if (fields.id) lastId = Number(fields.id); // the first block has an id and no event: keep it too
>             if (!fields.data) continue;
>             yield { event: fields.event, data: JSON.parse(fields.data) };
>           }
>         }
>       } catch {
>         // the connection was cut
>       }
>     }
>     await new Promise((resolve) => setTimeout(resolve, 3000)); // then reconnect, with the last id
>   }
> }
>
> for await (const { event, data } of streamEvents({ sessionId: 'SESSION_ID' })) {
>   if (event === 'final') {
>     console.log(`[${data.start}s] ${data.text}`);
>   } else if (event === 'ended') {
>     console.log('Session over:', data.status, data.end_reason);
>     break;
>   }
> }
> ```

### Polling

[`GET /tiktok/live/transcribe/{session_id}`](https://docs.vidnavigator.com/api-reference/endpoint/tiktok-live-transcribe-session.md) returns the session and its final sentences, numbered by `seq`. Pass the `pagination.next_after_seq` of an answer as `after_seq` of the next call to receive only what was said since.

```python Python
import time

after_seq = 0
while True:
    resp = client.get_tiktok_live_transcription(session_id, after_seq=after_seq)
    for segment in resp.data.segments:
        print(f"[{segment.start:.1f}s] {segment.text}")
    after_seq = resp.data.pagination.next_after_seq

    if resp.data.pagination.has_more:
        continue  # more sentences are ready: read them now
    if resp.data.session.status in ("ended", "failed"):
        break  # every sentence was read
    time.sleep(2)
```

```javascript JavaScript
let afterSeq = 0;
while (true) {
  const { session, segments, pagination } = await vn.getTikTokLiveTranscription(sessionId, { after_seq: afterSeq });
  for (const s of segments) console.log(`[${s.start}s] ${s.text}`);
  afterSeq = pagination.next_after_seq;

  if (pagination.has_more) continue; // more sentences are ready: read them now
  if (session.status === 'ended' || session.status === 'failed') break; // every sentence was read
  await new Promise((resolve) => setTimeout(resolve, 2000));
}
```

```bash cURL
curl "https://api.vidnavigator.com/v1/tiktok/live/transcribe/SESSION_ID?after_seq=0" \
  -H "X-API-Key: YOUR_API_KEY"
```

Polling is also how to catch up after an interruption: `seq` starts at 1 and has no gaps, so `after_seq` set to the last `seq` you stored returns exactly what you missed. To follow many rooms, prefer the event stream: one connection instead of one poll per room.

### Webhook

Pass a `webhook_url` when you start the session, and the final sentences are POSTed to your server as they come:

- `tiktok_live_transcribe.segments`: the final sentences since the previous delivery, in order, at most one delivery every two seconds;
- `tiktok_live_transcribe.ended`: sent once, when the session is over, with its `status`, `end_reason` and `error`.

Deliveries are signed like every VidNavigator webhook. Verify the signature, then read the JSON body:

```python Python (Flask)
import json

from flask import Flask, request
from vidnavigator import WebhookSignatureError, verify_webhook_signature

app = Flask(__name__)
SIGNING_SECRET = "YOUR_SIGNING_SECRET"  # Studio → API

@app.post("/hooks/vidnavigator")
def vidnavigator_webhook():
    raw_body = request.get_data()
    try:
        verify_webhook_signature(raw_body, request.headers.get("X-VidNavigator-Signature"), SIGNING_SECRET)
    except WebhookSignatureError:
        return "invalid signature", 400

    event = json.loads(raw_body)
    data = event["data"]
    if event["type"] == "tiktok_live_transcribe.segments":
        for segment in data["segments"]:
            save_sentence(data["session_id"], segment["seq"], segment["text"])  # your own storage
    elif event["type"] == "tiktok_live_transcribe.ended":
        print(data["session_id"], data["status"], data["end_reason"])
    return "", 200
```

```javascript Node.js (Express)
import express from 'express';
import { verifyWebhookSignature } from 'vidnavigator';

const app = express();
const SIGNING_SECRET = process.env.VIDNAVIGATOR_WEBHOOK_SECRET; // Studio → API

app.post('/hooks/vidnavigator', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verifyWebhookSignature(req.body, req.get('X-VidNavigator-Signature'), SIGNING_SECRET)) {
    return res.status(400).send('Invalid signature');
  }
  res.sendStatus(200);

  const { type, data } = JSON.parse(req.body);
  if (type === 'tiktok_live_transcribe.segments') {
    for (const segment of data.segments) {
      saveSentence(data.session_id, segment.seq, segment.text); // your own storage
    }
  } else if (type === 'tiktok_live_transcribe.ended') {
    console.log(data.session_id, data.status, data.end_reason);
  }
});
```

What to know:

- The account default webhook set in Studio is **not** used for LIVE transcription: only a session started with `webhook_url` is delivered.
- A delivery that fails is tried a second time, then skipped. After five skipped deliveries in a row, no more are sent for this session. Nothing is lost: every sentence stays readable by polling, and `seq` tells you what is missing.
- Store sentences by `session_id` and `seq`: a delivery received twice then changes nothing.
- Partial sentences are not sent to webhooks.

The payloads and headers are on the [Webhooks](https://docs.vidnavigator.com/webhooks.md#tiktok-live-transcription) page.

## Final and Partial Sentences

A **final** sentence is delivered once and never changes. It has its number in the session (`seq`), its `start` and `end` in seconds from the start of the session, its `language`, and a `timestamp` (UTC).

With `include_partials: true`, you also receive the sentence **being said**, updated several times a second: `partial` events on the event stream, and `partial` on the polling answer. A partial can still change, and the final sentence that follows replaces it. Use partials to display live captions; store and process final sentences only.

```text
event: partial
data: {"session_id":"3f0c1c1e-7a52-4d0e-9a3b-0d2f8c1b7e55","text":"I'm from","start":103.29}

id: 4821
event: final
data: {"session_id":"3f0c1c1e-7a52-4d0e-9a3b-0d2f8c1b7e55","seq":57,"start":103.29,"end":104.88,"text":"I'm from Gambia.","language":"en","timestamp":"2026-12-03T11:20:03.290Z"}
```

A `partial` has no `id` and is not replayed after a reconnection.

## Speakers

With `include_speakers: true`, each final sentence has a `speaker` label: `A`, `B`, and so on. Labels tell the voices of the session apart. They do not identify people: `A` is not a name, and the same person can get another label in another session, or after an interruption of the stream.

## Languages

The language is detected sentence by sentence, so a LIVE that mixes languages is transcribed as it goes: each final sentence carries its own `language`.

When you know the language spoken, pass it as `language` (two letters: `en`, `fr`, `ar`...): the transcript is more accurate. Leave it out for a LIVE in several languages.

## Stop a Session

```python Python
client.stop_tiktok_live_transcription(session_id)
```

```javascript JavaScript
await vn.stopTikTokLiveTranscription(sessionId);
```

```bash cURL
curl -X DELETE "https://api.vidnavigator.com/v1/tiktok/live/transcribe/SESSION_ID" \
  -H "X-API-Key: YOUR_API_KEY"
```

The session ends within a few seconds (`end_reason: "stopped"`). Stopping a session that is already over changes nothing.

To see which rooms you are transcribing, list your sessions: `client.list_tiktok_live_transcriptions()` in Python, `vn.listTikTokLiveTranscriptions()` in JavaScript, or [`GET /tiktok/live/transcribe`](https://docs.vidnavigator.com/api-reference/endpoint/tiktok-live-transcribe-list.md).

## How a Session Ends

A session runs until one of these happens. Its `status` is then `ended`, and `end_reason` says which:

| `end_reason`           | What happened                                                                        |
| ---------------------- | ------------------------------------------------------------------------------------ |
| `live_ended`           | The LIVE ended.                                                                      |
| `stopped`              | You stopped the session.                                                             |
| `max_duration_reached` | `max_duration_minutes` of the LIVE were transcribed. Start a new session to go on.   |
| `insufficient_credits` | Your organization ran out of credits.                                                |
| `no_reader`            | Nobody followed the session for 2 minutes (see below). Start a new session to go on. |

**A session must be followed.** Closing your connection (Ctrl+C, a crash, `break` out of the SDK's loop) does not stop a session: it goes on, billed, until something ends it. A session that **nobody follows for 2 minutes** stops by itself with `end_reason: "no_reader"`, so a client that disappears pays 2 minutes at the most. A session is followed while:

- an event stream is open on it, or on your whole organization (without `session_id`);
- you read it (`GET /tiktok/live/transcribe/{session_id}`), or start the same room again;
- its `webhook_url` still accepts the deliveries (a webhook skipped five times in a row no longer counts).

Listing your sessions does not count. A reconnecting stream, or a poll every few seconds, keeps a session going; to end one at once, [stop it](#stop-a-session).

A session that could not go on is `failed` instead, and `error.code` says why: `stream_unavailable` (the sound of the LIVE could not be read), `transcription_unavailable` (the transcription could not go on) or `internal_error`. What was transcribed before the failure stays readable. A failed session is not restarted for you: if the LIVE is still on air, start a new one.

You learn that a session is over from the `ended` event of the stream, from `session.status` when polling, or from the `tiktok_live_transcribe.ended` webhook.

## When a Session Cannot Start

| Answer                         | What to do                                                                                                                                                                                                                 |
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `503 system_overload`          | The service cannot take one more room right now. Nothing was started and nothing was charged. Retry after `retry_after_seconds`, given in the answer (and in the `Retry-After` header).                                    |
| `429 too_many_active_sessions` | Your organization transcribes as many rooms at once as its plan allows (see the [limits](https://docs.vidnavigator.com/api-reference/rate-limiting.md#tiktok-live-transcription)). Stop a session, or wait for one to end. |
| `409 live_ended`               | The LIVE is not on air: there is nothing to transcribe.                                                                                                                                                                    |
| `404 live_not_found`           | The room or the account does not exist, or the account has never gone LIVE.                                                                                                                                                |
| `502 live_room_unavailable`    | TikTok did not serve the room. Retry in a moment.                                                                                                                                                                          |
| `403 access_denied`            | LIVE transcription is not enabled for your organization. [Contact us](https://docs.vidnavigator.com/contact.md).                                                                                                           |

```python Python
import time

from vidnavigator import LiveEndedError, SystemOverloadError

def start(room_id, attempts=5):
    for _ in range(attempts):
        try:
            return client.start_tiktok_live_transcription(room_id=room_id)
        except SystemOverloadError as exc:
            time.sleep(exc.retry_after_seconds or 60)  # nothing was started: try again later
        except LiveEndedError:
            return None  # the LIVE is not on air
        # TooManyActiveSessionsError is left to the caller: stop a session, or wait for one to end
    raise RuntimeError("The service is still full: try again later")
```

```javascript JavaScript
import { LiveEndedError, SystemOverloadError } from 'vidnavigator';

async function start(roomId, attempts = 5) {
  for (let i = 0; i < attempts; i++) {
    try {
      return await vn.startTikTokLiveTranscription({ room_id: roomId });
    } catch (err) {
      if (err instanceof SystemOverloadError) {
        // nothing was started: try again later
        await new Promise((resolve) => setTimeout(resolve, (err.retry_after_seconds ?? 60) * 1000));
      } else if (err instanceof LiveEndedError) {
        return null; // the LIVE is not on air
      } else {
        throw err; // TooManyActiveSessionsError: stop a session, or wait for one to end
      }
    }
  }
  throw new Error('The service is still full: try again later');
}
```

## Retention

A session and its sentences stay readable for **24 hours** after it ends, by polling or by replaying the event stream (`after=0`). Store what you need to keep longer.

## Billing

A session is billed for the time actually transcribed, plus one TikTok request when it starts. Reading, listing and stopping cost nothing. Rates and rules: [Usage Costs](https://docs.vidnavigator.com/api-reference/usage-costs.md#tiktok-live-transcription).

A LIVE can last many hours: set `max_duration_minutes` to what you need, and stop the sessions you no longer read.

## Next Steps

> [card] [LIVE Transcription reference](https://docs.vidnavigator.com/api-reference/endpoint/tiktok-live-transcribe.md)
>
> Parameters, the session object, and every error.

> [card] [Event stream reference](https://docs.vidnavigator.com/api-reference/endpoint/tiktok-live-transcribe-events.md)
>
> The events, and how to resume a connection.

> [card] [Searching TikTok](https://docs.vidnavigator.com/guides/tiktok-search.md)
>
> Find LIVE rooms by keyword and country, or check one streamer.

> [card] [Webhooks](https://docs.vidnavigator.com/webhooks.md)
>
> Payloads, signature verification and deliveries.
