Skip to main content
This page describes fish-audio 0.2.0. Release notes are on GitHub.

Install

The SDK requires Node.js 20 or later. It ships ES module and CommonJS builds with type declarations for both, so import and require work:
The WebSocket methods, textToSpeech.convertRealtime() and speechToText.convertRealtime(), run in Node.js only: browsers cannot set the Authorization header on a WebSocket.

Client

Import and initialize the client:
Without apiKey, the client reads FISH_API_KEY from the environment. Pass baseUrl to send requests to another address, such as a proxy.

Request options

Every HTTP method takes a requestOptions object as its last argument. Of the realtime WebSocket methods, speechToText.convertRealtime() takes only abortSignal and timeoutInSeconds (there, the time to connect, 30 seconds by default), and textToSpeech.convertRealtime() takes none.

Text to Speech

convert()

Generate speech from text.
Parameters: request (TTSRequest), model? (Backends, default "s2.1-pro"), requestOptions?
Returns: Promise<ReadableStream<Uint8Array>>

convertRealtime()

Realtime streaming TTS over WebSocket.
Parameters: request (TTSRequest with text: ""), textStream (Iterable<string> or AsyncIterable<string>), backend? (Backends, default "s2.1-pro")
Returns: Promise<RealtimeConnection> (EventEmitter-like connection) emitting RealtimeEvents

Speech to Text

convert()

Transcribe audio to text.
Parameters: request (STTRequest), requestOptions? (for example timeoutInSeconds)
Returns: STTResponse
model is sent as the model header. Without it, and without a model header in requestOptions.headers, the request is served and billed as transcribe-1. See Speech to Text.

convertRealtime()

Transcribe live audio with transcribe-stream-1 (Preview) over a WebSocket, turn by turn. Send 16-bit little-endian mono PCM in chunks of 20–40 ms as you capture it. The SDK opens the session, sends each chunk as the audio source yields it, and ends the session when the source is exhausted. It runs in Node.js only.
To make speech.pcm from a recording, run ffmpeg -i input.mp3 -ac 1 -ar 16000 -f s16le speech.pcm. Parameters: request (RealtimeSTTRequest, {} is valid), audioStream (Iterable or AsyncIterable of Buffer, typed array or ArrayBuffer chunks), requestOptions? (abortSignal, and timeoutInSeconds for opening the connection, default 30)
Returns: RealtimeSTTStream, synchronously. Iterate it with for await to read events; the loop ends after session_done.
RealtimeSTTRequest fields: A top-level field (eager, drafts, diarize, terms) wins over the same setting in turn_detection, results or context. By default each transcript starts with a speaker tag such as <|speaker:0|>; pass diarize: false for plain text. Events are narrowed by type. Their fields use the protocol’s snake_case names, such as turn_index and audio_end_ms: See Realtime Speech to Text for how turns work and the WebSocket reference for every field.

Control methods

RealtimeSTTStream sends control messages while the session runs:
send(message) sends any control message, and a control message such as { type: "agent_speaking", speaking: true } yielded by the audio source is sent at that position in the audio. The SDK does not send keepalives for you.

Errors

Errors are thrown from the for await loop:
  • RealtimeSTTError when the server ends the session or the connection is lost. It carries errorType (such as unsupported_audio; match on this field), statusCode, requestId, closeCode and recoverable. statusCode and closeCode are optional: a lost connection has no HTTP status, so they can be undefined.
  • When the connection is refused: BadRequestError (400), UnauthorizedError (401), ForbiddenError (403) or NotFoundError (404), and FishAudioError with a statusCode for any other status, such as 402 or 429. All of them extend FishAudioError, so err.statusCode works for each.
  • The audio source’s own error when the audio source throws.

Close the session and stop the audio source

Leaving the loop early, or calling stream.close(), closes the connection. When the session ends for any reason, the stream calls return() on the audio source’s iterator and does not wait for it, so close() never hangs on the source. An async generator that is suspended on a read cannot be interrupted this way: its return() only runs after that read settles. If your source can block, such as a microphone, give it an AbortSignal and abort it when you are done with the session:
Racing the read only stops the generator from waiting; recorder.close() in the finally block stops the capture, so release your device there. controller.abort() on its own ends the audio: the session then finishes with session_done, as it does when the source is exhausted. To end the session itself from outside the loop, pass { abortSignal } as the third argument of convertRealtime(): when the signal aborts, the stream closes and throws the signal’s reason.

Voices

List/search available voice models.
Parameters: request? (ModelListRequest)
Returns: ModelListResponse

get()

Get model details.
Parameters: voiceId (string)
Returns: ModelEntity

ivc.create()

Create a new voice model from audio samples.
Parameters: request (ModelCreateRequest)
Returns: ModelEntity

update()

Update model metadata.
Parameters: voiceId (string), request (UpdateModelRequest)
Returns: UpdateVoiceResponse

delete()

Delete a model.
Parameters: voiceId (string)
Returns: DeleteVoiceResponse

User

get_api_credit()

Check API credit balance.
Returns: APICreditResponse

get_package()

Get subscription package details.
Returns: PackageResponse

Request Classes

TTSRequest

Text-to-speech parameters.
Fields: text, reference_id, references, format, mp3_bitrate, opus_bitrate, sample_rate, prosody, latency, chunk_length, normalize, temperature, top_p, max_new_tokens, repetition_penalty, min_chunk_length, condition_on_previous_chunks, early_stop_threshold, features
  • opus_bitrate is in bits per second: -1000 (automatic), 24000, 32000, 48000 or 64000.
  • latency is "low", "normal" or "balanced".
  • For multi-speaker dialogue (S2 family only), pass an array of voice IDs as reference_id and mark the turns in the text:

STTRequest

Speech-to-text parameters.
Fields: audio, model?, language?, ignore_timestamps?

ReferenceAudio

Reference audio for zero-shot voice cloning. audio is typed as File. At runtime the SDK also accepts a Blob, but TypeScript rejects one, so wrap a Blob or a Buffer in a File (new File([blob], "reference.wav")):
Fields: audio, text. Pass a flat array as references for one speaker, or one array per speaker for multi-speaker dialogue.

Prosody

Speed and volume control (ProsodyControl).
Fields: speed (0.5–2.0), volume (-20 to 20), normalize_loudness? (S2 family only)

Backends

The TTS model, sent as the model header.
The default is s2.1-pro. Any other string is accepted, so a model released after this SDK version works without an update. s1 is deprecated and retires on December 31, 2026; see Migrate from S1.

Response Classes

STTResponse

Transcription result.

ASRSegment

Timestamped text segment. Fields: text (string), start (number, seconds), end (number, seconds)

ModelEntity

Voice model information. Fields: _id, title, description, state, visibility, created_at, updated_at, tags

ModelListResponse

List response for voices. Fields: items (ModelEntity[]), total (number)

APICreditResponse

API credit information. Fields: _id (string), user_id (string), credit (string), created_at (string), updated_at (string), has_phone_sha256 (boolean), has_free_credit? (boolean)

PackageResponse

Subscription package details. Fields: user_id (string), type (string), total (number), balance (number), created_at (string), updated_at (string), finished_at (string)

WebSocket Classes

RealtimeEvents

Events emitted by textToSpeech.convertRealtime() connections.

RealtimeSTTStream

The session returned by speechToText.convertRealtime(): an async iterable of RealtimeSTTEvent, with the control methods above.

Event Classes

StartEvent

Stream start event. Fields: event (“start”), request (TTSRequest)

TextEvent

Text chunk event. Fields: event (“text”), text (string)

FlushEvent

Flush text chunks event. Fields: event (“flush”)

CloseEvent

Stream close event. Fields: event (“stop”)

Exceptions

FishAudioError

Generic error with statusCode, body, rawResponse. statusCode is undefined when the SDK has no usable response, such as after a timeout or a network error.

UnprocessableEntityError

Thrown for 422 (invalid parameters). Extends FishAudioError; body.detail, when the API sends it, lists the fields that failed. It is the only error class tied to a status that the HTTP methods throw: every other status is a plain FishAudioError, so branch on statusCode.

FishAudioTimeoutError

Exported for request timeouts; it extends Error, not FishAudioError. In fish-audio 0.2.0 with the fetch built into Node.js, a request that times out reaches you as a FishAudioError with no statusCode instead, so handle both.

RealtimeSTTError

A realtime speech-to-text session failed. Extends FishAudioError with errorType, requestId, closeCode and recoverable.

Upgrade notes

Upgrading from 0.1.0 to 0.2.0:
  • The default TTS model is now s2.1-pro, for textToSpeech.convert() and textToSpeech.convertRealtime(). The published 0.1.0 package sent the deprecated s1 when you passed no model. To use another model, pass it: convert(request, "s2-pro").
  • opus_bitrate is in bits per second. Code that passes 24, 32, 48 or 64 no longer compiles: multiply the value by 1000.
  • ReferenceAudio.audio must be a File (a Blob also works at runtime, but the TypeScript type is File). A Buffer or Uint8Array passed with a type cast now fails with ref.audio.arrayBuffer is not a function. Wrap it: new File([buffer], "sample.mp3").
  • Model names are no longer cast. Backends names s2.1-pro, s2.1-pro-free and drama-3 and accepts any other string, so remove as Backends casts. speech-1.5, speech-1.6, agent-x0 and s1-mini no longer autocomplete.
  • Node.js 20 or later is required.
  • require("fish-audio") works. In 0.1.0 it threw ReferenceError: exports is not defined in ES module scope.
  • Select the speech-to-text model with model. convert({ audio, model: "transcribe-1-pro" }) replaces { headers: { model: "transcribe-1-pro" } }, which still works.