Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .mintlify/skills/fish-audio-sdk/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
- **TTS models:** the API supports `s1` (deprecated), `s2-pro`, `s2.1-pro` (recommended for production), and `s2.1-pro-free` (free tier). Do not choose `s1` for new code: S1 is deprecated and will be retired on December 31, 2026. After that date, requests that specify `s1` are served by `s2.1-pro` (migration: `https://docs.fish.audio/developer-guide/models-pricing/migrate-from-s1`). However, the Python SDK types `model` as only `s1` and `s2-pro` (plus the deprecated `speech-1.x`), default `s2-pro`. The JS package on npm (`fish-audio` 0.1.0) types `backend` without `s2-pro` or `s2.1-pro` and defaults it to `"s1"` at runtime (its README says `"s2-pro"`), so in JS always pass `backend` explicitly. Both SDKs forward the model value without runtime validation, so `"s2.1-pro"` works over the wire. Static type checkers will flag it, so add `# type: ignore` (Python) / an `as` cast (TS), or use the `fish-audio-api` skill for raw calls. `speech-1.5` / `speech-1.6` are **deprecated**. In Python pass `model="s2-pro"` (keyword); in JS pass the **positional** `backend` argument.
- **ASR models:** use `transcribe-1-pro` (recommended: speaker turns, long recordings, emotion cues). Neither SDK has an ASR `model` argument: send the `model: transcribe-1-pro` HTTP header on every request (Python `RequestOptions(additional_headers=...)`, JS `requestOptions.headers`). A request without it is served and billed as `transcribe-1`, the model for short recordings. See [references/speech-to-text.md](references/speech-to-text.md).
- **Audio formats:** `mp3` (default), `wav`, `pcm`, `opus`.
- **Playback in examples:** `play()` shells out to a system audio tool: Python uses **ffmpeg/ffplay** (or `mpv`), JS uses **ffplay**. It is for local/desktop use; in a server, `save()` to a file or stream the bytes instead. See [references/installation.md](references/installation.md).

Check warning on line 24 in .mintlify/skills/fish-audio-sdk/SKILL.md

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'ffplay'?

## Quick start: Python

Expand Down Expand Up @@ -83,7 +83,7 @@

| Task | Reference |
| ---------------------------------------------------------------- | ------------------------------------------------------------ |
| Install, auth, playback deps, verify a key | [references/installation.md](references/installation.md) |

Check warning on line 86 in .mintlify/skills/fish-audio-sdk/SKILL.md

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'deps'?
| Text-to-Speech (convert, stream, formats, prosody, model select) | [references/text-to-speech.md](references/text-to-speech.md) |
| Voice cloning (instant references + persistent voice models) | [references/voice-cloning.md](references/voice-cloning.md) |
| Speech-to-Text (models, timestamps, fields the SDK drops) | [references/speech-to-text.md](references/speech-to-text.md) |
Expand All @@ -100,6 +100,7 @@
| Text-to-Speech | `client.tts.convert(text=...)` → `bytes` | `client.textToSpeech.convert({ text })` |
| TTS HTTP stream | `client.tts.stream(...)` → `AudioStream` | (use `convert`; realtime streaming is `convertRealtime`) |
| Realtime WebSocket | `client.tts.stream_websocket(text_stream)` | `client.textToSpeech.convertRealtime(request, textStream)` |
| TTS + word timestamps | `client.tts.convert_with_timestamps(text=...)` | not in the SDK; call the HTTP endpoint |
| Speech-to-Text | `client.asr.transcribe(audio=...)` | `client.speechToText.convert({ audio })` |
| List voice models | `client.voices.list()` | `client.voices.search()` |
| Get voice model | `client.voices.get(id)` | `client.voices.get(id)` |
Expand All @@ -107,12 +108,13 @@
| Update / delete voice | `client.voices.update(id, ...)` / `delete(id)` | `client.voices.update(id, ...)` / `delete(id)` |
| Credit balance | `client.account.get_credits()` | `client.user.get_api_credit()` |
| Subscription package | `client.account.get_package()` | `client.user.get_package()` |
| Choose model | `model="s2-pro"` keyword arg | positional `backend` arg, e.g. `convert(req, "s2-pro")` |

Check warning on line 111 in .mintlify/skills/fish-audio-sdk/SKILL.md

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'arg'?

Check warning on line 111 in .mintlify/skills/fish-audio-sdk/SKILL.md

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'arg'?
| ASR model (header) | `RequestOptions(additional_headers=...)` | `convert(req, { headers: { model: "transcribe-1-pro" } })` |

## Decision shortcuts

- **Audio from text** → `tts.convert` (Python) / `textToSpeech.convert` (JS).
- **Audio plus the time of each word (captions, highlighting)** → `tts.convert_with_timestamps` / `tts.stream_with_timestamps` (Python, `fish-audio-sdk` 1.6.0+). See "Word timestamps" in `references/text-to-speech.md`.
- **Reuse a saved voice** → pass `reference_id` (the voice model `id`).
- **Clone a voice instantly from a clip** → pass `references=[ReferenceAudio(audio=..., text=...)]` (Python) / `references: [{ audio, text }]` (JS). See [voice-cloning](references/voice-cloning.md).
- **Persistent custom voice to reuse** → create a voice model, then use its `id` as `reference_id`.
Expand Down
24 changes: 24 additions & 0 deletions .mintlify/skills/fish-audio-sdk/references/text-to-speech.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
audio2 = client.tts.convert(text="Second line.", config=config)
```

`TTSConfig` fields (with defaults): `format="mp3"`, `sample_rate=None`, `mp3_bitrate=128` (`64|128|192`), `opus_bitrate=32` (kbps: `-1000|24|32|48|64`, `-1000`=auto), `normalize=True`, `chunk_length=200`, `latency="balanced"`, `reference_id=None`, `references=[]`, `prosody=None`, `top_p=0.7`, `temperature=0.7`, `max_new_tokens=1024`, `repetition_penalty=1.2`, `min_chunk_length=50`, `condition_on_previous_chunks=True`, `early_stop_threshold=1.0`.

Check warning on line 64 in .mintlify/skills/fish-audio-sdk/references/text-to-speech.md

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'kbps'?

### Streaming the HTTP response

Expand All @@ -76,6 +76,30 @@

Async: every method mirrors onto `AsyncFishAudio`; `await client.tts.convert(...)`, and `client.tts.stream(...)` must be awaited before iterating with `async for`.

### Word timestamps (`fish-audio-sdk` 1.6.0+)

`convert_with_timestamps()` / `stream_with_timestamps()` take the same keyword arguments as `convert()` / `stream()` and call `POST /v1/tts/stream/with-timestamp`.

```python
result = client.tts.convert_with_timestamps(text="Hello! Welcome to Fish Audio.")
result.audio # bytes, complete audio
result.segments # list[TTSTimestampSegment(text, start, end)], seconds from the start of result.audio
result.duration # float | None, length reported by the API

with client.tts.stream_with_timestamps(text="Long passage...", format="opus") as stream:
for event in stream: # TTSTimestampEvent
sink.write(event.audio) # may be b"" on a closing event that only corrects timings
show(stream.segments) # timings so far on the full-audio timeline; re-read after every event
```

- Segments are words without punctuation; Chinese/Japanese come back one character per segment; numbers follow the spoken reading (`$42.50` → `42`, `50`). Never match segments against the input text.
- Text the API can't time (only punctuation, or only a tag like `[sigh]`): audio is complete, `segments == []`, `duration is None`. Guard before formatting `duration`.
- `stream.collect()` returns the same `TTSTimestampResult`; call it instead of iterating. After iteration has started it raises `RuntimeError`.
- Leaving the `with` block (e.g. `break`) closes the connection; without `with`, call `stream.close()` (`await stream.aclose()` async).
- Async: `await client.tts.convert_with_timestamps(...)`; `async with await client.tts.stream_with_timestamps(...) as stream: async for event in stream: ...`.
- Do not add `event.chunk_audio_offset_sec` to `stream.segments` or `result.segments`: they are already global. (`event.alignment` is the raw per-chunk snapshot, chunk-local times, `None` when absent.)
- No timestamps from `stream_websocket()`, and the JS SDK has no timestamp method; use the HTTP/WebSocket endpoints from the `fish-audio-api` skill.

## JavaScript: `client.textToSpeech`

`convert(request, backend?, requestOptions?)` resolves to a `ReadableStream<Uint8Array>` you can `play()` or pipe to a file. `backend` is the **second positional** argument, **not** a named option. Always pass it: the npm release (`fish-audio` 0.1.0) defaults it to the deprecated `"s1"` at runtime, although its README says `"s2-pro"`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ iconType: "solid"
timeline editing.
</Note>

<Tip>
The Python SDK (`fish-audio-sdk` 1.6.0 or later) parses this stream for you:
`client.tts.convert_with_timestamps()` and
`client.tts.stream_with_timestamps()` return the audio with every segment
already on the complete audio timeline. See [Word
timestamps](/features/text-to-speech#word-timestamps).
</Tip>

## How the Stream Works

The response is a Server-Sent Events stream. Every event includes:
Expand Down
8 changes: 8 additions & 0 deletions developer-guide/getting-started/changelog.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@
icon: "clock-rotate-left"
rss: true
---
<Update label="Python SDK 1.6.0: word timestamps" description="November 25, 2026" tags={["Fish Audio"]}>
## Python SDK 1.6.0: word timestamps

`fish-audio-sdk` 1.6.0 adds text to speech with word-level timestamps. `client.tts.convert_with_timestamps()` returns the audio with the start and end time of each word, and `client.tts.stream_with_timestamps()` yields audio and timings as they arrive, in both the sync and async clients. Timings are already on the timeline of the complete audio, also for long text generated in several chunks.

[Word timestamps](/features/text-to-speech#word-timestamps) | [Generate speech with captions](/developer-guide/sdk-guide/cookbook/speech-with-captions) | [Release notes](https://github.com/fishaudio/fish-audio-python/releases/tag/fish-audio-sdk-v1.6.0)
</Update>

<Update label="Voice Agents React Native SDK and widget" description="November 21, 2026" tags={["Fish Audio"]}>
## Voice Agents React Native SDK and widget

Expand Down Expand Up @@ -63,7 +71,7 @@
<Update label="Live 3 full-duplex model" description="November 10, 2026" tags={["Fish Audio"]}>
## Live 3 full-duplex model

Live 3 is our full-duplex speech model for Voice Agents (`voice.engine: "live3"`). Instead of waiting for a caller to finish before generating speech, a single model listens while it speaks and decides when to backchannel, wait, respond, or stop on real interruptions and mid-turn corrections.

Check warning on line 74 in developer-guide/getting-started/changelog.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'backchannel'?

New agents start on Live 3 by default for English sessions. Choose from eight built-in Live 3 voices (`clara`, `nora`, `harper`, `patricia`, `owen`, `marco`, `milo`, `jonah`) or any Voice Library voice, and tune turn-taking with situation prompts (`P2` phone support, `DT` drive-thru, or `AIR` airline). Sessions in other languages automatically use the agent's cascade text-to-speech model.

Expand Down Expand Up @@ -93,7 +101,7 @@
<Update label="Realtime Speech to Text (transcribe-stream-1)" description="October 20, 2026" tags={["Fish Audio"]}>
## Realtime Speech to Text (`transcribe-stream-1`)

Stream live 16-bit PCM audio over `wss://api.fish.audio/v1/asr/realtime` for turn-by-turn transcription powered by `transcribe-stream-1`. Beyond live `draft` transcripts with `settled_text`, Smart Turn Detection (`auto`, `vad`, and `manual` modes) handles eager end-of-turn signals, backchannel detection, and background awareness, alongside conversation context (`context.terms`, `context_add`, `context.history`), speaker diarization, and optional sound event tags (`results.tag_audio_events`).

Check warning on line 104 in developer-guide/getting-started/changelog.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'backchannel'?

Check warning on line 104 in developer-guide/getting-started/changelog.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'diarization'?

Sessions run up to 60 minutes. `transcribe-stream-1` is also available as a speech recognition model in Voice Agents (`fish_audio:transcribe-stream-1`).

Expand Down Expand Up @@ -173,7 +181,7 @@
<Update label="Fish Audio S1" description="June 2025" tags={["Fish Audio"]}>
## Fish Audio S1

Historic rebrand from Fish Speech to Fish Audio. #1 ranking on TTS-Arena2 with industry-leading performance.

Check warning on line 184 in developer-guide/getting-started/changelog.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'rebrand'?

S1 (4B params): 0.008 WER, 0.004 CER - Available on Fish Audio Playground
S1-mini (0.5B params): 0.011 WER, 0.005 CER - Open source on Hugging Face
Expand Down Expand Up @@ -218,7 +226,7 @@

Infrastructure improvements focused on Docker optimization and multi-platform builds.

Updated PyTorch version and replaced audio backend from sox for better performance. Enhanced CI/CD pipeline with buildx support and fixed various Docker-related issues.

Check warning on line 229 in developer-guide/getting-started/changelog.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'sox'?

Check warning on line 229 in developer-guide/getting-started/changelog.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'buildx'?
</Update>

<Update label="v1.4.0" description="September 12, 2024" tags={["Fish Speech"]}>
Expand Down Expand Up @@ -256,7 +264,7 @@
<Update label="v1.1.1" description="June 8, 2024" tags={["Fish Speech"]}>
## v1.1.1

Breaking changes: Replaced zibai with uvicorn for API server, new text-splitter with byte-based length calculation, and license change to CC-BY-NC-SA 4.0.

Check warning on line 267 in developer-guide/getting-started/changelog.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'zibai'?

Check warning on line 267 in developer-guide/getting-started/changelog.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'uvicorn'?

Added Apple Silicon (MPS) support, Windows one-click installation, and automatic model downloading with resume capability. Improved WebUI with better file selection and download progress indicators.
</Update>
Expand All @@ -266,7 +274,7 @@

Added VITS decoder integration with full streaming support and queue management for real-time audio generation.

Introduced internationalization (i18n) with Spanish translation and improved Windows packaging. Optimized GPU memory usage and CPU-only inference performance while adding LoRA support to the Gradio UI.

Check warning on line 277 in developer-guide/getting-started/changelog.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'Gradio'?
</Update>

<Update label="v1.0.0" description="April 30, 2024" tags={["Fish Speech"]}>
Expand All @@ -274,7 +282,7 @@

Major milestone release introducing new VQ-GAN architecture with VITS decoder support, LoRA fine-tuning, and streaming inference capabilities.

Breaking changes include removal of the Rust-based data server, new tokenizer replacing phonemizer, and updated model architecture (VQ + DiT + Reflow). Achieved 4x memory reduction during loading and added WebUI for training and annotation.

Check warning on line 285 in developer-guide/getting-started/changelog.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'phonemizer'?
</Update>

<Update label="v0.2.0" description="December 23, 2023" tags={["Fish Speech"]}>
Expand All @@ -282,5 +290,5 @@

First public release of Fish Speech featuring a complete text-to-speech pipeline with VQ-GAN audio codec and LLAMA-based language model.

Includes multi-language support (Chinese, English, Japanese), Gradio WebUI for inference, HTTP API server, and Docker support. Added special optimizations for Chinese users including mirror downloads and localized documentation.

Check warning on line 293 in developer-guide/getting-started/changelog.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'Gradio'?
</Update>
139 changes: 139 additions & 0 deletions developer-guide/sdk-guide/cookbook/speech-with-captions.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
---
title: "Generate speech with SRT/VTT captions"
description: "Generate narration with word-level timestamps from the Python SDK, group the words into caption cues, and write the audio with matching SRT and WebVTT files"
icon: "closed-captioning"
---

import Prerequisites from "/snippets/prerequisites.mdx";

## Prerequisites

<Prerequisites />

This recipe needs `fish-audio-sdk` 1.6.0 or later: `pip install -U fish-audio-sdk`.

## Recipe

[`tts.convert_with_timestamps()`](/features/text-to-speech#word-timestamps) returns the audio together with timed segments, so the captions match the generated speech exactly. Segments are word-level (one character in Chinese and Japanese) and carry no punctuation, so the recipe groups consecutive segments into caption-sized cues before it writes them. Segment `start` / `end` are in **seconds**; SRT wants `HH:MM:SS,mmm` (comma), WebVTT wants `HH:MM:SS.mmm` (dot).

The recipe starts a new cue after a pause longer than 0.6 seconds, or when the cue would grow past 42 characters or 6 seconds. It joins words with a space, except between Chinese or Japanese characters. A segment can have `start` equal to `end`, so a cue with no duration gets a short one that ends no later than the next cue starts. If the next cue starts at the same millisecond, that cue is moved 1 ms later, so every cue ends after it starts and cues never overlap.

```python Python
import re

from fishaudio import FishAudio
from fishaudio.utils import save

client = FishAudio()

MAX_CHARS = 42 # longest cue text, in characters
MAX_MS = 6000 # longest cue, in milliseconds
MAX_GAP_MS = 600 # a longer pause between words starts a new cue
MIN_MS = 500 # display time for a cue whose words have no duration

# Chinese and Japanese are written without spaces between words.
NO_SPACE = re.compile(r"[぀-ヿ㐀-䶿一-鿿]")

TEXT = (
"Welcome to the museum. The east wing opens at nine and closes at six. "
"Guided tours leave every hour from the main hall, and the café on the "
"second floor serves lunch until three."
)


def join_words(left: str, right: str) -> str:
if NO_SPACE.match(left[-1]) and NO_SPACE.match(right[0]):
return left + right
return f"{left} {right}"


def group_cues(segments) -> list[dict]:
"""Group word-level segments into cues, with start and end in milliseconds."""
cues = []
for segment in segments:
word = segment.text.strip()
if not word:
continue
start, end = round(segment.start * 1000), round(segment.end * 1000)
if cues:
cue = cues[-1]
text = join_words(cue["text"], word)
if (
start - cue["end"] <= MAX_GAP_MS
and len(text) <= MAX_CHARS
and end - cue["start"] <= MAX_MS
):
cue["text"], cue["end"] = text, max(cue["end"], end)
continue
cues.append({"start": start, "end": end, "text": word})

# A segment can have start == end. Give a cue with no duration a short one,
# ending no later than the next cue starts, so every cue ends after it starts.
for i, cue in enumerate(cues):
if cue["end"] <= cue["start"]:
end = cue["start"] + MIN_MS
if i + 1 < len(cues):
end = min(end, cues[i + 1]["start"])
cue["end"] = max(end, cue["start"] + 1)
Comment thread
lumpinif marked this conversation as resolved.
Resolved
# If the next cue starts at the same millisecond, move it 1 ms later
# so the two cues don't overlap.
if i + 1 < len(cues) and cues[i + 1]["start"] < cue["end"]:
cues[i + 1]["start"] = cue["end"]
return cues


def format_timestamp(ms: int, separator: str) -> str:
"""HH:MM:SS,mmm for SRT (separator ","), HH:MM:SS.mmm for WebVTT (".")."""
hours, ms = divmod(ms, 3_600_000)
minutes, ms = divmod(ms, 60_000)
seconds, ms = divmod(ms, 1000)
return f"{hours:02d}:{minutes:02d}:{seconds:02d}{separator}{ms:03d}"


result = client.tts.convert_with_timestamps(text=TEXT, format="mp3")
save(result.audio, "narration.mp3")

# Text without words (only punctuation or a sound tag such as "[sigh]") still
# produces audio, but no timings. Parts of a long text can also lack timings.
if not result.segments:
raise SystemExit("No word timings for this text; captions not written.")

cues = group_cues(result.segments)

# SRT: 1-based index, comma decimal separator, blank line between cues.
with open("narration.srt", "w", encoding="utf-8") as srt:
for i, cue in enumerate(cues, start=1):
start = format_timestamp(cue["start"], ",")
end = format_timestamp(cue["end"], ",")
srt.write(f"{i}\n{start} --> {end}\n{cue['text']}\n\n")

# WebVTT: same cues, "WEBVTT" header, dot decimal separator.
with open("narration.vtt", "w", encoding="utf-8") as vtt:
vtt.write("WEBVTT\n\n")
for cue in cues:
start = format_timestamp(cue["start"], ".")
end = format_timestamp(cue["end"], ".")
vtt.write(f"{start} --> {end}\n{cue['text']}\n\n")

# duration is None when the end of the audio has no timings.
length = f"{result.duration:.2f}s" if result.duration is not None else "length not reported"
print(f"Wrote narration.mp3 ({length}) with {len(cues)} cues")
```

Play `narration.mp3` with `narration.vtt` as its text track, or load `narration.srt` next to it in a video editor. Tune `MAX_CHARS`, `MAX_MS`, and `MAX_GAP_MS` for your player and audience.

Captions show the words as they were spoken after [text normalization](/features/text-to-speech#language), without punctuation: `$42.50` becomes the two words `42` and `50`, not the text you sent. To show your original wording, keep your own sentences and use the segment times only to decide when each sentence starts and ends.

<Tip>
Long text is generated in several chunks. The SDK already places every segment
on the timeline of the complete audio, so you don't need to add
`chunk_audio_offset_sec` yourself as the [API
reference](/api-reference/endpoint/openapi-v1/text-to-speech-stream-with-timestamps)
describes for raw requests.
</Tip>

## Related

- [Text to Speech: word timestamps](/features/text-to-speech#word-timestamps)
- [Transcribe audio to SRT/VTT captions](/developer-guide/sdk-guide/cookbook/transcribe-to-captions), the same cues from a recording instead of generated speech
- [Text to Speech Stream with Timestamps API](/api-reference/endpoint/openapi-v1/text-to-speech-stream-with-timestamps)
3 changes: 2 additions & 1 deletion docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,8 @@
"group": "Text to Speech",
"pages": [
"developer-guide/sdk-guide/cookbook/streaming-to-file",
"developer-guide/sdk-guide/cookbook/telephony-8khz-audio"
"developer-guide/sdk-guide/cookbook/telephony-8khz-audio",
"developer-guide/sdk-guide/cookbook/speech-with-captions"
]
},
{
Expand Down
53 changes: 52 additions & 1 deletion features/text-to-speech.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

<CardGroup cols={2}>
<Card title="Voiceovers & narration" icon="film">
Audiobooks, explainers, ads, and video narration.

Check warning on line 26 in features/text-to-speech.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'Audiobooks'?

Check warning on line 26 in features/text-to-speech.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'explainers'?
</Card>
<Card title="Conversational AI" icon="comments">
Speak an assistant's replies. Pair with [streaming](/features/realtime-streaming) for low latency.
Expand Down Expand Up @@ -163,13 +163,14 @@

### Generation methods (Python)

The Python SDK exposes three ways to generate, depending on whether you have the full text upfront and how you want to consume the audio:
The Python SDK exposes these ways to generate, depending on whether you have the full text upfront, how you want to consume the audio, and whether you need word timings:

| Method | Returns | Use it for |
|---|---|---|
| `tts.convert()` | complete audio `bytes` | most cases: you have the text, you want the file |
| `tts.stream()` | `AudioStream` (iterate chunks, or `.collect()`) | memory-efficient transfer of large audio; write chunks to disk as they arrive |
| `tts.stream_websocket()` | iterator of audio `bytes` | text arriving in real time (LLM tokens, live captions) |
| `tts.convert_with_timestamps()` / `tts.stream_with_timestamps()` | audio with word timings | captions and word highlighting; see [Word timestamps](#word-timestamps) |

```python
# Memory-efficient: write each chunk as it arrives instead of buffering
Expand All @@ -181,6 +182,56 @@

For real-time text streaming with `stream_websocket()`, see [Realtime Streaming](/features/realtime-streaming).

### Word timestamps

`tts.convert_with_timestamps()` returns the audio together with the time each word is spoken, for captions, highlighting words during playback, or editing on a timeline. It needs `fish-audio-sdk` 1.6.0 or later (`pip install -U fish-audio-sdk`), takes the same arguments as `convert()`, and calls [`POST /v1/tts/stream/with-timestamp`](/api-reference/endpoint/openapi-v1/text-to-speech-stream-with-timestamps).

```python
from fishaudio import FishAudio
from fishaudio.utils import save

client = FishAudio()
result = client.tts.convert_with_timestamps(text="Hello! Welcome to Fish Audio.")
save(result.audio, "hello.mp3")

for segment in result.segments:
print(f"{segment.start:.2f}-{segment.end:.2f} {segment.text}")
if result.duration is not None:
print(f"{result.duration:.2f} seconds")
```

```text
0.00-0.56 Hello
0.96-1.44 Welcome
1.44-1.60 to
1.60-1.92 Fish
1.92-2.56 Audio
2.69 seconds
```

- `start` and `end` are seconds from the start of `result.audio`, also for long text that is generated in several chunks.
- A segment is usually one word without punctuation. Text written without spaces, such as Chinese, comes back one character per segment, and numbers follow the spoken reading after [normalization](#language): `$42.50` gives the segments `42` and `50`. Don't expect segments to match your input text.
- When the API can't time the text, for example text that is only punctuation or a sound tag such as `[sigh]`, the audio is still complete, but `segments` is `[]` and `duration` is `None`. In a long text, only some parts can lack timings: `segments` then has the timed words, and `duration` is `None` if the end of the audio has no timings. `duration` is the length the API reports, not one measured from the audio.

To use audio and timings while they arrive, call `tts.stream_with_timestamps()`. Each event carries the next piece of audio in `event.audio`, which can be empty, and `stream.segments` holds the timings received so far on the timeline of the complete audio:

```python
with client.tts.stream_with_timestamps(text="A long passage...", format="opus") as stream:
with open("out.opus", "wb") as f:
for event in stream:
f.write(event.audio)
if stream.segments:
latest = stream.segments[-1]
print(f"timed up to {latest.end:.2f}s: {latest.text}")
```

- Read `stream.segments` again after each event instead of keeping an earlier copy: later events can still correct the last entries.
- Leaving the `with` block closes the connection, so you can stop early with `break`. Without `with`, call `stream.close()`.
- `stream.collect()` returns the same result as `convert_with_timestamps()`. Call it instead of iterating, not after: once iteration has started it raises `RuntimeError`.
- With `AsyncFishAudio`, await both methods and iterate with `async with await client.tts.stream_with_timestamps(...) as stream:` and `async for event in stream:`.

`stream_websocket()` doesn't return timestamps; for timestamps over a WebSocket, use the [WebSocket endpoint](/api-reference/endpoint/openapi-v1/text-to-speech-live-with-timestamps) directly. To write captions from the segments, see [Generate speech with SRT/VTT captions](/developer-guide/sdk-guide/cookbook/speech-with-captions).

### Instant voice cloning (reference audio)

Instead of a saved `reference_id`, pass raw audio plus its transcript to clone a voice on the fly, with no training step. Best with a clean 10–30s sample.
Expand All @@ -197,16 +248,16 @@

To reuse a voice across many requests, [clone it once](/features/voice-cloning) and pass the resulting `reference_id` instead.

### Format & bitrate

Check warning on line 251 in features/text-to-speech.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'bitrate'?

Pick a format for your delivery channel, and tune bitrate to trade size against quality:

Check warning on line 253 in features/text-to-speech.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'bitrate'?

| Format | Notes |
|---|---|
| `mp3` (default) | good size/quality balance; set `mp3_bitrate` to `64`, `128`, or `192` |
| `wav` | uncompressed, highest quality; set `sample_rate` (e.g. `44100`) |
| `pcm` | raw samples, no container; for low-latency playback and telephony pipelines |
| `opus` | efficient for streaming; bitrate is automatic (`opus_bitrate=-1000`) |

Check warning on line 260 in features/text-to-speech.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'bitrate'?

```python
from fishaudio.types import TTSConfig
Expand Down Expand Up @@ -310,7 +361,7 @@
```

- **Default**: omit `language`, or send `"auto"` or an empty string, and the language is detected for each text chunk. This is the same behavior as before the field was added.
- **Regional conventions**: Spanish without a region follows Spain conventions, so `$300` becomes "trescientos dólares" and decimals use a comma. Send `es-MX` for Mexican readings ("pesos", "punto"). For Traditional Chinese, send `zh-TW`, which uses its own rules. Portuguese follows Brazilian conventions, with or without the `BR` region.

Check warning on line 364 in features/text-to-speech.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'trescientos'?

Check warning on line 364 in features/text-to-speech.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'punto'?
- **Tags without rules**: a tag with no dedicated normalization rules skips normalization instead of failing. See [Supported normalization languages](#supported-normalization-languages).
- **Mixed-language text**: leave `language` unset.
- **`normalize: false`**: `language` then only affects word timestamps.
Expand Down Expand Up @@ -342,7 +393,7 @@
| Swedish | `sv`, `sv-SE`, `sv-FI` |
| Malay | `ms`, `ms-MY` |

Each row has its own rules, so the tag you pick changes the readings. For example, with `es` or `es-ES`, `$300` is read as "trescientos dólares" and the `0.9` in `0.9%` as "cero coma nueve". With `es-MX`, they are read as "trescientos pesos" and "cero punto nueve". In the same way, `zh-TW` uses Traditional Chinese rules, not the Simplified Chinese ones.

Check warning on line 396 in features/text-to-speech.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'trescientos'?

Check warning on line 396 in features/text-to-speech.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'nueve'?

Check warning on line 396 in features/text-to-speech.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'trescientos'?

Check warning on line 396 in features/text-to-speech.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'punto'?

Check warning on line 396 in features/text-to-speech.mdx

View check run for this annotation

Mintlify / Mintlify Validation (hanabiaiinc) - vale-spellcheck

Vale.Spelling

Did you really mean 'nueve'?

- Any other tag skips normalization, with no error, and the text is still synthesized as written. Today that includes `zh-HK`, `yue`, `pt-PT`, `es-419`, `es-US`, and `id`.
- With `language` unset, the language of each chunk is auto-detected among the languages above. Chinese written mostly in Traditional characters uses the Traditional Chinese rules. Portuguese, Turkish, Tagalog, and Malay are detected only when the detection is confident, so set `language` for short texts in these languages. Malay is close to Indonesian, so many longer Malay sentences are missed as well, and a missed sentence can have its numbers read with another language's rules; for text entirely in Malay, set `language` to `ms` regardless of length. Chunks whose language can't be detected are synthesized without normalization.
Expand Down
Loading
Loading