Skip to content

About

The official Python library for the Fish Audio API.

Topics

Resources

Contributing

Stars

238 stars

Watchers

3 watching

Forks

Repository files navigation

Fish Audio Python SDK

Fish Audio Python SDK

PyPI version Python Version PyPI - Downloads codecov License

The official Python library for the Fish Audio API

Documentation: Python SDK Guide | API Reference

Important

Changes to PyPI Versioning

For existing users on Fish Audio Python SDK, please note that the starting version is now 1.0.0. The last version before this was 2025.6.3. You may need to adjust your version constraints accordingly.

The original API in the fish_audio_sdk package has NOT been removed, but you will not receive any updates if you continue using the old versioning scheme.

The simplest fix is to update your dependency to fish-audio-sdk>=1.0.0 to continue receiving updates, or by pinning to a specific version like fish-audio-sdk==1.0.0 when installing via your package manager. There are no changes to the API itself in this transition.

If you're using the legacy fish_audio_sdk and would like to switch to the newer, more robust fishaudio package, see the migration guide to upgrade.

Installation

pip install fish-audio-sdk

# To play audio without FFmpeg (adds sounddevice and soundfile)
pip install "fish-audio-sdk[utils]"

Authentication

Get your API key from fish.audio/app/api-keys:

export FISH_API_KEY=your_api_key_here

Or provide directly:

from fishaudio import FishAudio

client = FishAudio(api_key="your_api_key")

Quick Start

Synchronous:

from fishaudio import FishAudio
from fishaudio.utils import save

client = FishAudio()

# Generate audio (MP3 by default) and save it to a file
audio = client.tts.convert(text="Hello, world!")
save(audio, "output.mp3")

Asynchronous:

import asyncio
from fishaudio import AsyncFishAudio
from fishaudio.utils import save


async def main():
    client = AsyncFishAudio()
    audio = await client.tts.convert(text="Hello, world!")
    save(audio, "output.mp3")


asyncio.run(main())

Playing the audio (optional): play runs the ffplay program from FFmpeg, which must be on your PATH; without it, play raises DependencyError. To play without FFmpeg, install the [utils] extra (on Linux, sounddevice also needs the PortAudio library, such as libportaudio2) and pass use_ffmpeg=False.

from fishaudio.utils import play

with open("output.mp3", "rb") as f:
    audio = f.read()

play(audio)  # needs ffplay on PATH
# Or, without FFmpeg, after pip install "fish-audio-sdk[utils]":
# play(audio, use_ffmpeg=False)

Core Features

Text-to-Speech

Selecting a model:

# S3 Pro ("s3-pro") is used when no model is set
audio = client.tts.convert(text="Default model speech")

# S2.1 Pro: the default in 1.7.x and earlier
s21_audio = client.tts.convert(
    text="S2.1 Pro speech",
    model="s2.1-pro",
)

# S3 Pro Free: the same model at $0 under fair-use limits, for testing and
# prototyping, including on a $0 API balance. The earlier name "s2.1-pro-free"
# is still accepted and is served by s3-pro-free.
free_audio = client.tts.convert(
    text="Free speech",
    model="s3-pro-free",
)

# Drama 3: our most expressive model (uses API credit)
drama_audio = client.tts.convert(
    text="Expressive speech",
    model="drama-3",
)

With custom voice:

# Use a specific voice by ID
audio = client.tts.convert(
    text="Custom voice", reference_id="802e3bc2b27e49c2995d23ef70e6ac89"
)

With speed control:

audio = client.tts.convert(
    text="Speaking faster!",
    speed=1.5,  # 1.5x speed
)

Language of the text:

# On s2.1-pro, "$300" is read as pesos with es-MX and as dólares with es.
# s3-pro, the default, normalizes a regional tag with its base language and
# reads this "$300" as pesos with es and es-MX alike.
audio = client.tts.convert(
    text="La entrada cuesta $300.",
    model="s2.1-pro",
    language="es-MX",
)

language is a BCP-47 tag such as en, es-MX or zh-CN. Regional conventions (es-MX against es) apply on s2.1-pro, s2-pro and s1; s3-pro reads a regional tag as its base language. It only changes how numbers, dates, units and symbols are spelled out before synthesis (and word-timestamp alignment); it does not change the voice or accent. Without it, the API detects the language of each chunk, which is also the right choice for text that mixes languages. It is accepted by every text-to-speech method and by TTSConfig; on stream_websocket it applies to the whole session. See supported normalization languages.

Reusable configuration:

from fishaudio.types import TTSConfig, Prosody

config = TTSConfig(
    prosody=Prosody(speed=1.2, volume=-5),
    reference_id="933563129e564b19a115bedd57b7406a",
    format="wav",
    latency="balanced",  # or "normal" (quality), "low" (earlier first audio on s3-pro)
)

# Reuse across generations
audio1 = client.tts.convert(text="First message", config=config)
audio2 = client.tts.convert(text="Second message", config=config)

Chunk-by-chunk processing:

# Stream and process chunks as they arrive
for chunk in client.tts.stream(text="Long content..."):
    send_to_websocket(chunk)

# Or collect all chunks
audio = client.tts.stream(text="Hello!").collect()

Word-level timestamps:

# Audio plus the start and end time of every word, for captions, highlighting or lip-sync
result = client.tts.convert_with_timestamps(text="Hello! Welcome to Fish Audio.")
save(result.audio, "output.mp3")

for segment in result.segments:
    print(f"{segment.start:.2f}s - {segment.end:.2f}s  {segment.text}")

# Or use audio and timings while they arrive
with client.tts.stream_with_timestamps(text="Long content...", format="opus") as stream:
    for event in stream:
        send_to_player(event.audio)
        update_captions(stream.segments)  # timings so far, in seconds from the start

Text without words (only punctuation, or a sound tag such as [sigh]) still produces audio, but the API has no timings for it: segments is then empty and result.duration is None.

s1 and transcribe-1 are deprecated and will be retired on December 31, 2026. After that date, requests that specify them are served by s3-pro and transcribe-2-pro. Using a deprecated model emits a FutureWarning; with Python's default warning filters it is shown once per calling line. A coroutine scheduled with asyncio.create_task or gather runs from asyncio's code, so its warning points there and is shown once in all. A transcription that names no model runs on the API's default model (transcribe-1 until it is retired, transcribe-2-pro after) and emits a FutureWarning, shown as the deprecation warnings above are; pass a model (the model argument or a model header) to silence it. Write the model ID exactly, for example transcribe-2-pro: the API runs a name it does not know on its default model, and the SDK does not check names. A model that only an httpx request hook or auth flow adds is not seen, so such a request still gets the warning; if you also turn warnings into errors, pass model in the call. See Model Deprecations.

Learn more

Speech-to-Text

# transcribe-2-pro is the recommended model; without model, the request runs on transcribe-1,
# which is deprecated and will be retired on December 31, 2026 (then served by transcribe-2-pro),
# and emits a FutureWarning.
with open("meeting.wav", "rb") as f:
    result = client.asr.transcribe(audio=f.read(), model="transcribe-2-pro")

# On transcribe-2-pro, text keeps <|speaker:N|> markers; speaker_turns has clean text per speaker.
print(result.text)

# Word-level timestamps
for segment in result.segments:
    print(f"[{segment.start:.2f}s - {segment.end:.2f}s] {segment.text}")

# Speaker turns (transcribe-2-pro, returned with timestamps)
for turn in result.speaker_turns or []:
    print(f"[{turn.start:.2f}s - {turn.end:.2f}s] {turn.speaker}: {turn.text}")

# Language of the transcript, when the API returns it
print(result.language_code)  # e.g. "en"

# Plain transcript on transcribe-2-pro: no speaker markers, no cues such as [laughter]
with open("meeting.wav", "rb") as f:
    plain = client.asr.transcribe(
        audio=f.read(),
        model="transcribe-2-pro",
        diarize=False,
        tag_audio_events=False,
    )
print(plain.text)

The Pro models also take num_speakers, min_speakers and max_speakers (speaker-count hints), and transcribe-2-pro takes text_format="spoken" (numbers in words), verbatim=False (asks the model to leave out fillers and false starts) and keyterms=["Fish Audio", ...] (terms to spell as listed). Options left as None are not sent; the API ignores those a model does not use.

Learn more

Realtime (Preview): stream live audio to transcribe-stream-1 and get the transcript turn by turn. Send 16-bit mono PCM in 20–40 ms chunks as you capture it:

import wave


def audio_chunks():
    with wave.open("speech.wav", "rb") as wav:  # 16-bit mono PCM, 16 kHz
        while chunk := wav.readframes(640):  # 40 ms
            yield chunk


# diarize=False gives plain text; by default it starts with a speaker tag: "<|speaker:0|> Hello."
for event in client.asr.stream_websocket(
    audio_chunks(), sample_rate=16000, drafts=True, diarize=False
):
    if event.type == "draft":  # live text of the open turn, not final
        print("...", event.text)
    elif event.type == "committed":  # final transcript of the turn
        print(event.text)

With AsyncFishAudio, pass an async iterator and use async for. The returned stream also sends control messages during the session, such as stream.finalize() for push-to-talk and stream.agent_speaking(True) for voice agents.

Learn more

Real-time Streaming

Stream dynamically generated text for conversational AI and live applications:

Synchronous:

def text_chunks():
    yield "Hello, "
    yield "this is "
    yield "streaming!"


audio_stream = client.tts.stream_websocket(text_chunks(), latency="balanced")
play(audio_stream)

Asynchronous:

import asyncio
from fishaudio import AsyncFishAudio


async def text_chunks():
    yield "Hello, "
    yield "this is "
    yield "streaming!"


async def main():
    client = AsyncFishAudio()
    # stream_websocket is an async generator: iterate it, don't await the call
    audio_stream = client.tts.stream_websocket(text_chunks(), latency="balanced")
    with open("output.mp3", "wb") as f:
        async for chunk in audio_stream:
            f.write(chunk)


asyncio.run(main())

Learn more

Voice Cloning

Instant cloning:

from fishaudio.types import ReferenceAudio

# Clone voice on-the-fly
with open("reference.wav", "rb") as f:
    audio = client.tts.convert(
        text="Cloned voice speaking",
        references=[ReferenceAudio(audio=f.read(), text="Text spoken in reference")],
    )

Persistent voice models:

# Create voice model for reuse
with open("voice_sample.wav", "rb") as f:
    voice = client.voices.create(
        title="My Voice", voices=[f.read()], description="Custom voice clone"
    )

# Use the created model
audio = client.tts.convert(text="Using my saved voice", reference_id=voice.id)

Learn more

Resource Clients

Resource Description Key Methods
client.tts Text-to-speech convert(), stream(), convert_with_timestamps(), stream_with_timestamps(), stream_websocket()
client.asr Speech recognition transcribe(), stream_websocket()
client.voices Voice management list(), get(), create(), update(), delete()
client.account Account info get_credits(), get_package()

Tracing

To continue your trace in the Fish Audio API, send a W3C traceparent header on each request. Use one of the ways below. A traceparent that the OpenTelemetry instrumentation sends replaces one you set yourself.

With OpenTelemetry, configure a tracer provider and enable opentelemetry-instrumentation-httpx. HTTP calls and the WebSocket handshakes of tts.stream_websocket() and asr.stream_websocket() then carry the current trace: the same trace id, under a client span that the instrumentation creates. A WebSocket stream connects when you first iterate it, so iterate it inside your span.

from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor

HTTPXClientInstrumentor().instrument()

Without OpenTelemetry, pass the header with each call:

from fishaudio.core import RequestOptions, WebSocketOptions

headers = {"traceparent": traceparent}
audio = client.tts.convert(
    text="Hello!", request_options=RequestOptions(additional_headers=headers)
)
stream = client.tts.stream_websocket(
    text_chunks(), ws_options=WebSocketOptions(additional_headers=headers)
)

Or give the client an httpx_client with a request event hook, which runs for HTTP calls and WebSocket handshakes alike (with AsyncFishAudio, use an httpx.AsyncClient and an async hook). A client you pass in keeps its own settings, so set its timeout: httpx's default is 5 seconds.

import httpx


def add_traceparent(request):
    request.headers["traceparent"] = current_traceparent()


http_client = httpx.Client(
    base_url="https://api.fish.audio",
    timeout=240.0,
    event_hooks={"request": [add_traceparent]},
)
client = FishAudio(httpx_client=http_client)

Error Handling

from fishaudio.exceptions import (
    APIError,
    AuthenticationError,
    RateLimitError,
    FishAudioError,
)

try:
    audio = client.tts.convert(text="Hello!")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError:
    print("Rate limit exceeded")
except APIError as e:
    # Any other error response, such as 400 for a request the API rejects
    print(f"API error {e.status}: {e.message}")
except FishAudioError as e:
    print(f"Error: {e}")

A value the SDK can check before sending, such as a speed outside 0.5 to 2.0, raises pydantic's ValidationError instead, and no request is sent. fishaudio.exceptions.ValidationError is not raised by the SDK.

Every APIError carries the headers of the error response. When you contact support, include the trace id and the error code. Either can be absent.

from fishaudio.exceptions import APIError

try:
    audio = client.tts.convert(text="Hello!")
except APIError as e:
    print(e.headers.get("x-fish-trace-id"), e.headers.get("x-fish-error-code"))

A tts.stream_websocket handshake that the server refuses raises httpx_ws.WebSocketUpgradeError; read the same headers from e.response.headers.

Trace IDs

Responses to speech and transcription requests carry an x-fish-trace-id header. Include it when you contact support about a request, also one that succeeded but sounds wrong. The stream that tts.stream() returns has the response headers:

stream = client.tts.stream(text="Hello!")
try:
    audio = stream.collect()
finally:
    trace_id = stream.headers.get("x-fish-trace-id")  # None if not sent

The same headers attribute is on the streams of tts.stream_with_timestamps() and asr.stream_websocket() (empty until the connection opens on the first iteration), and on the results of tts.convert_with_timestamps() and asr.transcribe() (the latter also has request_id). tts.convert() returns only the audio; use tts.stream() as above when you need the headers. tts.stream_websocket() does not expose them yet.

Resources

License

This project is licensed under the Apache-2.0 License - see the LICENSE file for details.

About

The official Python library for the Fish Audio API.

Topics

Resources

Contributing

Stars

238 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages