fish-audio 0.2.0. Release notes are on GitHub.
Install
import and require work:
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: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 arequestOptions 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.request (TTSRequest), model? (Backends, default "s2.1-pro"), requestOptions? Returns:
Promise<ReadableStream<Uint8Array>>
convertRealtime()
Realtime streaming TTS over WebSocket.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.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 withtranscribe-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.
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 thefor await loop:
RealtimeSTTErrorwhen the server ends the session or the connection is lost. It carrieserrorType(such asunsupported_audio; match on this field),statusCode,requestId,closeCodeandrecoverable.statusCodeandcloseCodeare optional: a lost connection has no HTTP status, so they can beundefined.- When the connection is refused:
BadRequestError(400),UnauthorizedError(401),ForbiddenError(403) orNotFoundError(404), andFishAudioErrorwith astatusCodefor any other status, such as 402 or 429. All of them extendFishAudioError, soerr.statusCodeworks 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 callingstream.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:
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
search()
List/search available voice models.request? (ModelListRequest) Returns:
ModelListResponse
get()
Get model details.voiceId (string) Returns:
ModelEntity
ivc.create()
Create a new voice model from audio samples.request (ModelCreateRequest) Returns:
ModelEntity
update()
Update model metadata.voiceId (string), request (UpdateModelRequest) Returns:
UpdateVoiceResponse
delete()
Delete a model.voiceId (string) Returns:
DeleteVoiceResponse
User
get_api_credit()
Check API credit balance.APICreditResponse
get_package()
Get subscription package details.PackageResponse
Request Classes
TTSRequest
Text-to-speech parameters.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_bitrateis in bits per second:-1000(automatic),24000,32000,48000or64000.latencyis"low","normal"or"balanced".- For multi-speaker dialogue (S2 family only), pass an array of voice IDs as
reference_idand mark the turns in the text:
STTRequest
Speech-to-text parameters.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")):
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).
speed (0.5–2.0), volume (-20 to 20), normalize_loudness? (S2 family only)
Backends
The TTS model, sent as themodel header.
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 bytextToSpeech.convertRealtime() connections.
RealtimeSTTStream
The session returned byspeechToText.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 withstatusCode, body, rawResponse. statusCode is undefined when the SDK has no usable response, such as after a timeout or a network error.
UnprocessableEntityError
Thrown for422 (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 extendsError, 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. ExtendsFishAudioError 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, fortextToSpeech.convert()andtextToSpeech.convertRealtime(). The published 0.1.0 package sent the deprecateds1when you passed no model. To use another model, pass it:convert(request, "s2-pro"). opus_bitrateis in bits per second. Code that passes24,32,48or64no longer compiles: multiply the value by 1000.ReferenceAudio.audiomust be aFile(aBlobalso works at runtime, but the TypeScript type isFile). ABufferorUint8Arraypassed with a type cast now fails withref.audio.arrayBuffer is not a function. Wrap it:new File([buffer], "sample.mp3").- Model names are no longer cast.
Backendsnamess2.1-pro,s2.1-pro-freeanddrama-3and accepts any other string, so removeas Backendscasts.speech-1.5,speech-1.6,agent-x0ands1-minino longer autocomplete. - Node.js 20 or later is required.
require("fish-audio")works. In 0.1.0 it threwReferenceError: 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.

