Fish Audio API: Working TTS, Streaming and Error Handling
The Fish Audio API can turn Text into a finished MP3 or return Audio while your application continues supplying Text. This guide builds both paths with Windows PowerShell and Python, with explicit model and voice selection, bounded concurrency and error handling.
For a voiceover without building an integration, use the DIY AI voice generator. Follow the implementation below when your own application needs to request and receive Audio.
- Choose the speech model and a saved voice ID.
- Generate one short MP3, decode it and listen to the complete result.
- Add the Python batch worker or WebSocket path your application needs.
- Check failures, interruptions and S1 migration before deployment.
Verification scope: checked on 24 November 2026. The Python examples were exercised on Python 3.12 with SDK 1.4.0, simulated HTTP and WebSocket responses, and a locally generated Audio fixture. No live Fish generation or Windows execution was performed.
Pin the speech model separately from the voice.
Create an API key in your Fish Audio account’s developer area before starting. model chooses the speech engine, while reference_id chooses the saved voice. Copy the ID from the voice you intend to use; its display name is not the API identifier.
| Setting | Value used here | Purpose |
|---|---|---|
| HTTP endpoint | POST https://api.fish.audio/v1/tts | Generate speech from supplied Text |
| Authentication | Authorization: Bearer YOUR_API_KEY | Authorise the request |
| Model header | model: s2.1-pro | Select the paid speech engine explicitly |
| JSON body | text, reference_id, format, latency | Set the words, voice and output settings |
Fish’s text-to-speech API reference documents a potentially expensive fallback: an omitted or unrecognised model value selects s2.1-pro. The WebSocket endpoint documents the same behaviour. Validate model names in your application so a spelling mistake cannot choose the billing route.
These examples deliberately select paid s2.1-pro, so they require API credit. For an intentional free-tier test, change the setting to exactly s2.1-pro-free; Fish currently advertises free access through 30 November 2026, so recheck availability and terms. A web subscription does not establish your API balance. Our Fish Audio review covers the product and billing context.
Use Windows curl without saving an error as an MP3
Use Windows PowerShell 5.1 or PowerShell 7 with curl.exe and FFmpeg available on your PATH. Work in a new folder. The Python examples reuse the environment variables set here, so run those from the same PowerShell window.
Calling curl.exe avoids the curl alias in Windows PowerShell. Writing JSON to a UTF-8 file without a byte order mark also avoids putting JSON quotes, apostrophes and line breaks through the shell’s native-command quoting rules.
$ErrorActionPreference = "Stop"
Get-Command curl.exe, ffmpeg -ErrorAction Stop | Out-Null
$secret = Read-Host "Fish API key" -AsSecureString
$env:FISH_API_KEY = [System.Net.NetworkCredential]::new("", $secret).Password
$env:FISH_VOICE_ID = Read-Host "Voice ID"
$env:FISH_MODEL = "s2.1-pro"
if (-not $env:FISH_API_KEY -or -not $env:FISH_VOICE_ID.Trim()) {
throw "An API key and voice ID are required."
}
if ($env:FISH_MODEL -notin @("s2.1-pro", "s2.1-pro-free")) {
throw "Unsupported model: fix the configuration before sending."
}
$request = @{
text = "Your order number is four two seven. Delivery is on Tuesday."
reference_id = $env:FISH_VOICE_ID
format = "mp3"
latency = "normal"
} | ConvertTo-Json -Compress
[System.IO.File]::WriteAllText(
(Join-Path $PWD "fish-request.json"),
$request, [System.Text.UTF8Encoding]::new($false)
)
$part = "fish-curl.mp3.part"
$status = curl.exe --silent --show-error `
--connect-timeout 10 --max-time 90 `
--request POST "https://api.fish.audio/v1/tts" `
--header "Authorization: Bearer $env:FISH_API_KEY" `
--header "Content-Type: application/json" `
--header "model: $env:FISH_MODEL" `
--data-binary "@fish-request.json" `
--output $part --write-out "%{http_code}"
if ($LASTEXITCODE -ne 0) {
Remove-Item $part -ErrorAction SilentlyContinue
throw "Transport failed. No new MP3 was saved."
}
if ($status -ne "200") {
Move-Item $part "fish-error.txt" -Force
throw "HTTP $status. Inspect fish-error.txt before retrying."
}
ffmpeg -nostdin -v error -xerror -f mp3 -i $part -map 0:a:0 -f null -
if ($LASTEXITCODE -ne 0) {
Remove-Item $part -ErrorAction SilentlyContinue
throw "The response failed MP3 decoding."
}
Move-Item $part "fish-curl.mp3" -Force
Write-Host "Saved fish-curl.mp3. Listen to the whole clip."
A non-200 response is kept in fish-error.txt, where you can inspect it before changing the request. A successful response must pass MP3 decoding before it receives the final filename. Across these examples, an older completed file can remain after a failed rerun; only a new Saved message indicates success.
Open the resulting MP3 and listen to both sentences. Decoder success establishes that the Audio is readable. It cannot establish the intended voice, correct pronunciation or the presence of the final words.
Bound both concurrency and retries in the Python SDK
Use Python 3.11 or later for this setup. Pin the SDK so an upgrade does not silently change the implementation you checked. The distribution is named fish-audio-sdk, while these examples import its modern fishaudio interface.
py -m venv .venv
.\.venv\Scripts\python.exe -m pip install "fish-audio-sdk==1.4.0"
Save the following as fish_batch.py. It generates three short clips with at most two active requests and three attempts per clip. HTTP 429 and selected server errors receive delayed retries; authentication errors, payment errors and transport timeouts surface for investigation.
import asyncio
import os
import random
import subprocess
from pathlib import Path
from fishaudio import AsyncFishAudio
from fishaudio.exceptions import APIError
MODEL = os.environ["FISH_MODEL"]
VOICE_ID = os.environ["FISH_VOICE_ID"]
if MODEL not in {"s2.1-pro", "s2.1-pro-free"}:
raise ValueError("Choose an explicitly supported model")
if not VOICE_ID.strip():
raise ValueError("FISH_VOICE_ID is empty")
def validate_audio(path):
if path.stat().st_size == 0:
raise ValueError("Empty audio response")
subprocess.run(
["ffmpeg", "-nostdin", "-v", "error", "-xerror",
"-f", "mp3", "-i", str(path), "-map", "0:a:0",
"-f", "null", "-"],
check=True, capture_output=True, timeout=30,
)
async def render(client, gate, number, text):
for attempt in range(3):
try:
async with gate:
audio = await asyncio.wait_for(
client.tts.convert(
text=text, reference_id=VOICE_ID, model=MODEL,
format="mp3", latency="normal",
),
timeout=90,
)
break
except APIError as error:
retryable = error.status in {429, 500, 502, 503, 504}
if not retryable or attempt == 2:
raise
await asyncio.sleep(2 ** attempt + random.uniform(0, 0.5))
final = Path(f"fish-{number}.mp3")
part = final.with_suffix(".mp3.part")
try:
part.write_bytes(audio)
await asyncio.to_thread(validate_audio, part)
part.replace(final)
finally:
part.unlink(missing_ok=True)
return final.name
async def main():
texts = [
"Your order number is four two seven. Delivery is on Tuesday.",
"The total is nineteen pounds and fifty pence.",
"This is the final sentence. The recording is complete.",
]
gate = asyncio.Semaphore(2)
async with AsyncFishAudio(timeout=30) as client:
results = await asyncio.gather(
*(render(client, gate, i, text)
for i, text in enumerate(texts, 1)),
return_exceptions=True,
)
failed = False
for i, result in enumerate(results, 1):
if isinstance(result, Exception):
failed = True
print(f"Clip {i}: {type(result).__name__}; "
f"HTTP {getattr(result, 'status', 'n/a')}")
else:
print(f"Saved {result}")
if failed:
raise SystemExit(1)
if __name__ == "__main__":
asyncio.run(main())
.\.venv\Scripts\python.exe .\fish_batch.py
The numbered filenames suit a local test. In a service, include a unique job ID in each output path so separate workers cannot write to the same temporary file.
The semaphore covers the complete API call. Retrying jobs release their slot while waiting. The client has a 30-second network timeout, and each API attempt has a separate 90-second deadline. These are sample limits for short clips; set production deadlines based on your workload.
Fish’s published starter allowance is five simultaneous requests, shared across API keys on the account. Two workers leave some capacity for other work, but a semaphore only controls this process. Several web workers need a shared queue or limiter. For a large backlog, also bound the waiting queue instead of creating a task for every item at once.
In the inspected 1.4.0 package, setting RequestOptions.max_retries alone did not produce retries in a simulated 429 test. The loop above implements its own finite policy. Recheck retry ownership when upgrading; otherwise, two retry layers can multiply the number of attempts.
Use WebSocket streaming when Audio must arrive during generation
The inspected SDK 1.4.0 implementation of tts.stream() buffers its HTTP response before returning the Audio iterator. A local test with separate response chunks confirmed that behaviour. Use convert() for completed files and the WebSocket path below for progressive transfer. Recheck this implementation detail after upgrading.
Save this as fish_stream.py beside fish_batch.py. It imports the same model, voice and decoder check. The short Text generator stands in for your application’s incoming Text; the SDK handles the MessagePack protocol at wss://api.fish.audio/v1/tts/live.
import asyncio
from pathlib import Path
from fishaudio import AsyncFishAudio, WebSocketOptions
from fishaudio.types import FlushEvent
from fish_batch import MODEL, VOICE_ID, validate_audio
async def text_chunks():
yield "Your order is ready. "
yield FlushEvent()
yield "This is the final sentence. The recording is complete."
async def receive(client, part):
with part.open("wb") as output:
async for chunk in client.tts.stream_websocket(
text_chunks(), reference_id=VOICE_ID, model=MODEL,
format="mp3", latency="normal",
ws_options=WebSocketOptions(
keepalive_ping_timeout_seconds=30,
),
):
output.write(chunk)
async def main():
part = Path("fish-stream.mp3.part")
try:
async with AsyncFishAudio(timeout=30) as client:
await asyncio.wait_for(receive(client, part), timeout=90)
await asyncio.to_thread(validate_audio, part)
part.replace("fish-stream.mp3")
print("Saved fish-stream.mp3")
finally:
part.unlink(missing_ok=True)
if __name__ == "__main__":
asyncio.run(main())
.\.venv\Scripts\python.exe .\fish_stream.py
stream_websocket() is an async generator: iterate it directly without awaiting the call. The FlushEvent asks Fish to synthesise the buffered first sentence. Flush at a useful utterance boundary; forcing a flush after every small Text fragment can change the speech’s phrasing.
The example writes received chunks in order and saves a final MP3 only after successful stream completion and decoding. It does not play Audio through your speakers during generation. For live playback, feed one persistent decoder with a bounded Audio buffer. A network chunk is not necessarily an independently playable clip.
The 90-second limit bounds this demonstration session. A WebSocket keepalive timeout checks connection responsiveness; it does not replace an application deadline. In a voice Agent, apply an appropriate deadline to each conversational turn and cancel its Text producer and queued playback when the turn is interrupted.
Diagnose the failure before resending the same Text
| Failure | First check | Recovery |
|---|---|---|
| 400 or 404 | Request fields and saved voice ID | Correct the input or resource reference before resending. |
| 401 or 403 | API key and access to the voice | Fix authentication or permissions. Repeating the request will not fix access. |
| 402 | Selected model and API credit | Resolve the account balance or deliberately choose an available model. Avoid an automatic model switch. |
| 429 | All requests sharing the account | Reduce active work and retry with a finite delay policy. |
| 500, 502, 503 or 504 | Response details and repeated service failures | Use the bounded retry policy; surface the failure when attempts are exhausted. |
| Timeout, disconnect or broken stream | Whether Audio arrived and whether completion was confirmed | Discard the partial result. Investigate before starting a fresh generation. |
Fish documents that native API concurrency errors arrive without a Retry-After header. The batch example therefore uses exponential delays with a little random variation. Error bodies can also be plain Text or HTML, so do not assume that every failed request contains valid JSON.
A timeout leaves uncertainty about work already performed. Keep an application job ID and record each attempt; don’t assume repeating a request is deduplicated or free. Never append a restarted generation to the Audio from a failed stream.
When live speech breaks, save the received Audio and play it outside your application first. If that file is complete, inspect gaps between arriving chunks, the playback buffer and interruption handling. Compare complete sentences with smaller input fragments, and discard Audio queued for the previous turn. These checks separate a playback problem from missing input or an incomplete generation.
Useful logs include the job ID, requested model, voice ID, attempt count, status, first-audio time and completion time. Record input size with len(text.encode("utf-8")) when reconciling usage: Fish meters TTS input in UTF-8 bytes. Keep credentials out of those logs.
See more of our reporting in Google Top Stories, AI Overviews and AI Mode.
Migrate S1 prompts before the server changes their interpretation
Fish says S1 retires on 31 December 2026. After that date, requests specifying s1 are served by s2.1-pro. An integration can keep returning successful responses while its spoken output changes.
- Change the model everywhere. Include background workers, saved job templates and WebSocket configuration.
- Convert emotion controls. Replace S1’s
(happy)style with[happy]. Fish does not automatically translate the old tags. - Recheck loudness. S2.1 Pro applies loudness normalisation, with
prosody.normalize_loudnessdefaulting to true. Existing downstream processing may need adjustment. - Remove ineffective tuning assumptions. The migration documentation says
repetition_penaltyhas no effect on S2.1 Pro.
Keep a fixed acceptance script containing names, abbreviations, currency, dates, a deliberate pause and an easily recognised final sentence. Generate it with the same voice and settings before and after migration. Compare pronunciation, pacing, loudness and the ending, rather than accepting an HTTP 200 as evidence that the migration preserved behaviour.
Check the complete delivery path before release.
- Audio acceptance: generate a real clip, decode it, listen to the whole passage and record the model, voice, settings and SDK version alongside it.
- Failure acceptance: simulate a bad key, empty credit, repeated 429 responses and a disconnect after Audio begins. Check that each job stops or recovers as intended.
- Shared capacity: count active work across every process and keep the waiting queue bounded.
- Application access: keep the Fish key on your server. Browser requests should pass through your own authenticated endpoint and usage limits.
If provider choice is still open, our Fish Audio vs ElevenLabs comparison covers the quality and workflow trade-offs. Otherwise, run the acceptance script through the queue, storage and player your users will actually use.


