To provide convenient Typescript program integration for https://docs.fish.audio
npm install fish-audioInitialize a FishAudioClient to use APIs. Authenticate by setting FISH_API_KEY="your_api_key"
in your environment or pass it in.
Get your API key from fish.audio/app/api-keys.
import { FishAudioClient } from "fish-audio";
const fishAudio = new FishAudioClient();Sometimes, you may need to change our endpoint to another address. You can use
import { FishAudioClient } from "fish-audio";
const fishAudio = new FishAudioClient({apiKey: "your_api_key", baseUrl: "https://your-proxy-domain"});convert takes an optional second argument for the model name. It defaults to "s3-pro"; pass any other supported name when you need it, for example "s2.1-pro" to keep the previous default.
| Model | Notes |
|---|---|
s3-pro |
S3 Pro (default) |
s2.1-pro |
S2.1 Pro, the default before s3-pro |
s3-pro-free |
Free tier of s3-pro: the same model at $0 under fair-use limits |
s2.1-pro-free |
Earlier name of s3-pro-free, still accepted and served by it |
drama-3 |
Expressive model you direct in plain language |
s2-pro |
Previous generation |
s1 |
Deprecated, retires on 2026-12-31; requests that specify it are then served by s3-pro |
import { FishAudioClient, play } from "fish-audio";
const fishAudio = new FishAudioClient({ apiKey: "your_api_key" });
const request = { text: "Hello, world!" };
const audio = await fishAudio.textToSpeech.convert(request); // defaults to "s3-pro"
await play(audio);
const drama = await fishAudio.textToSpeech.convert(request, "drama-3");language is a BCP-47 tag for the language of your text, such as en, es-MX or zh-CN. It only changes how numbers, dates, units and symbols are spelled out before synthesis; it does not change the voice or accent. Leave it unset, or give null, "" or "auto", to let the API detect the language of each chunk, which is also the right choice for text that mixes languages. With normalize: false it does not change the audio. On convertRealtime it applies to the whole session.
// 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.
const audio = await fishAudio.textToSpeech.convert(
{
text: "La entrada cuesta $300.",
language: "es-MX",
},
"s2.1-pro",
);A tag without normalization rules, such as es-419 or english, gives no error: the text is then not normalized. A malformed tag is rejected: over 35 characters, or characters other than ASCII letters, digits, - and _. Use a tag from the supported normalization languages.
import type { TTSRequest } from "fish-audio";
const request: TTSRequest = {
text: "Hello, world!",
reference_id: "your_model_id",
};Or pass ReferenceAudio for zero-shot cloning:
import { readFile } from "node:fs/promises";
import type { ReferenceAudio, TTSRequest } from "fish-audio";
// File is a global in Node.js 20 and later.
const audioBuffer = await readFile("path/to/your/audio/file.mp3");
const referenceFile = new File([audioBuffer], "audio_file_name.mp3");
const referenceAudio: ReferenceAudio = {
audio: referenceFile,
text: "reference audio text"
};
const request: TTSRequest = {
text: "Hello, world!",
references: [referenceAudio]
};Pass an array of voice IDs and mark speaker turns in the text. This works with s3-pro, s2.1-pro, s2-pro and drama-3, not s1.
const request: TTSRequest = {
text: "<|speaker:0|>Hello!<|speaker:1|>Hi there!",
reference_id: ["speaker-a-id", "speaker-b-id"],
};
const audio = await fishAudio.textToSpeech.convert(request, "s3-pro");The TTS websocket provides real-time streaming.
import { FishAudioClient, FishAudioError, RealtimeEvents } from "fish-audio";
import { writeFile } from "fs/promises";
import path from "path";
// Simple async generator that yields text chunks to speak
async function* makeTextStream() {
const chunks = [
"Hello from Fish Audio! ",
"This is a realtime text-to-speech test. ",
"We are streaming multiple chunks over WebSocket.",
];
for (const chunk of chunks) {
yield chunk;
await new Promise((r) => setTimeout(r, 200));
}
}
const client = new FishAudioClient();
// For realtime, set text to "" and stream the content via textStream instead
const request = {
text: "",
reference_id: "your_model_id"
};
// Defaults to backend: "s3-pro"
const connection = await client.textToSpeech.convertRealtime(request, makeTextStream());
// Collect audio and write to a file when the stream ends
const chunks: Buffer[] = [];
connection.on(RealtimeEvents.OPEN, () => console.log("WebSocket opened"));
connection.on(RealtimeEvents.AUDIO_CHUNK, (audio: Uint8Array) => {
chunks.push(Buffer.from(audio));
});
let failed = false;
connection.on(RealtimeEvents.ERROR, (err) => {
failed = true;
// Log the message and the fields you need: the whole error object can
// include the response headers (cookies among them), the body and the URL.
const traceId = err instanceof FishAudioError ? err.rawResponse?.headers.get("x-fish-trace-id") : undefined;
console.error("WebSocket error:", err.message, traceId ? `(trace id ${traceId})` : "");
});
connection.on(RealtimeEvents.CLOSE, async () => {
if (failed) {
process.exitCode = 1;
return;
}
const outPath = path.resolve(process.cwd(), "out.mp3");
await writeFile(outPath, Buffer.concat(chunks));
console.log("Saved to", outPath);
});CLOSE marks the end of a stream. When the server fails a stream, textStream throws, or the connection closes during it, ERROR is emitted before CLOSE, so always attach an ERROR listener: like any Node.js "error" event, one with no listener is thrown. Nothing of a stream is emitted after its CLOSE, or after you call connection.close().
The error ERROR carries:
UnauthorizedError, or anotherFishAudioErrorwith astatusCode, when the server refuses the connection, as for realtime speech to text. The message is the API's reason, such asHTTP 401: Invalid Token. A refusal is the stream's onlyERROR: if the connection is lost while its body is still arriving, the message is the status phrase (HTTP 401: Unauthorized) andbodyholds what arrived.RealtimeTTSErrorwhen the stream fails after the connection was made: the server sent an error (itserrormessage, such asReference not found, orfinishwith reasonerror), or the connection closed before the stream finished (closeCode; 1006 means the connection was lost, by whichever side). ItsrawResponseis the response the server sent to the handshake; its headers carry the trace id.- Any other error as it is, not wrapped: the socket's own error when the connection cannot be made (
codesuch asECONNREFUSED), the decoder's error for a message that cannot be decoded, your text source's own error whentextStreamthrows, and an error from encoding the start request.
After a stream that the server finished, the connection stays open: you can send another StartEvent on it, or call connection.close() when you no longer need it. After a stream that failed, the SDK closes the connection; call convertRealtime() again for the next one. The protocol has no stream id, so the SDK cannot tell a message of one stream that arrives late from a message of the next; messages that arrive while no stream is running are dropped.
import { FishAudioClient } from "fish-audio";
import { readFile } from "node:fs/promises";
const fishAudio = new FishAudioClient();
const audioFile = new File([await readFile("/path/to/your/audio/file.mp3")], "file.mp3");
try {
const result = await fishAudio.speechToText.convert({
audio: audioFile,
});
console.log("Transcription:", result.text);
console.log("Duration (s):", result.duration);
console.log("Segments:", result.segments);
} catch (err) {
console.error("STT request failed:", err);
}Unless a model header is configured, convert runs on the API's default model, transcribe-1. transcribe-1 is deprecated and retires on 2026-12-31; requests it serves are then served by transcribe-2-pro. A request that names transcribe-1 emits a Node.js DeprecationWarning, and so does a request that sends no model, because it runs on the API's default model, which is transcribe-1 until that date; each notice comes once. To silence the second one, pass any model, as the argument or as a model header. A model added outside the SDK, such as by a wrapper around the global fetch or by a proxy, is not seen, so that request still gets the notice. Pass model to choose another one, such as the recommended transcribe-2-pro; it takes precedence over a model header:
const result = await fishAudio.speechToText.convert({
audio: audioFile,
model: "transcribe-2-pro",
});transcribe-2-pro marks speakers (<|speaker:0|>) and sound cues ([laughter]) in text by default. For a plain transcript, turn both off:
const { text } = await fishAudio.speechToText.convert({
audio: audioFile,
model: "transcribe-2-pro",
diarize: false,
tag_audio_events: false,
});The Pro models (transcribe-1-pro, transcribe-2-pro) also take diarize: "auto" (the default) or true, the speaker-count hints num_speakers, min_speakers and max_speakers, and, on transcribe-2-pro only, text_format ("written" or "spoken"), verbatim and keyterms (up to 128 terms to spell as listed). Other models ignore these fields. The API checks the values and answers an invalid one with a 400 that names the field. With ignore_timestamps: false and diarize not false, the result has speaker_turns, who spoke when:
const result = await fishAudio.speechToText.convert({
audio: audioFile,
model: "transcribe-2-pro",
ignore_timestamps: false,
num_speakers: 2,
});
for (const turn of result.speaker_turns ?? []) {
console.log(`[${turn.start.toFixed(2)}s] ${turn.speaker}: ${turn.text}`);
}convertRealtime streams live audio to transcribe-stream-1 over a WebSocket and returns the transcript turn by turn. Send 16-bit little-endian mono PCM in chunks of 20–40 ms as you capture it. The returned stream is an async iterable of events; narrow them by type.
import { FishAudioClient } from "fish-audio";
import { createReadStream } from "fs";
const fishAudio = new FishAudioClient();
// Raw 16-bit mono PCM at 16 kHz, 40 ms (1280 bytes) per chunk.
// From a file this sends faster than real time; a microphone yields chunks as it captures them.
async function* audioChunks() {
yield* createReadStream("speech.pcm", { highWaterMark: 1280 });
}
// diarize: false gives plain text. By default the text starts with a speaker tag: "<|speaker:0|> Hello."
const stream = fishAudio.speechToText.convertRealtime(
{ sample_rate: 16000, drafts: true, diarize: false },
audioChunks(),
);
for await (const event of stream) {
if (event.type === "draft") {
console.log("...", event.text); // live text of the open turn, not final
} else if (event.type === "committed") {
console.log(event.text); // final transcript of the turn
}
}The session ends with a session_done event once the audio source is exhausted. 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:
async function* microphone(signal: AbortSignal) {
const recorder = openRecorder(); // your own capture code
try {
while (!signal.aborted) {
let stop!: () => void;
const aborted = new Promise<undefined>((resolve) => {
stop = () => resolve(undefined);
});
signal.addEventListener("abort", stop, { once: true });
let chunk: Uint8Array | undefined;
try {
// read() resolves with the next 20–40 ms of PCM.
chunk = await Promise.race([recorder.read(), aborted]);
} finally {
signal.removeEventListener("abort", stop);
}
if (chunk === undefined) {
break; // aborted while waiting for audio
}
yield chunk;
}
} finally {
recorder.close(); // releases the device, and a read that is still pending
}
}
const controller = new AbortController();
const stream = fishAudio.speechToText.convertRealtime({ diarize: false }, microphone(controller.signal));
try {
for await (const event of stream) {
if (event.type === "committed") console.log(event.text);
}
} finally {
controller.abort(); // stops the microphone, however the loop ended
}Racing the read only stops the generator from waiting; it is recorder.close() in the finally block that 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.
The stream also sends control messages while the session runs:
await stream.finalize(); // commit the open turn now (push-to-talk, with turn_detection: "manual")
await stream.agentSpeaking(true); // voice agents: your agent started speaking
await stream.addContext([{ role: "assistant", text: "Which day works for you?" }]);
await stream.configure({ turn_detection: { mode: "vad", silence_timeout_ms: 900 } });
await stream.keepalive(); // a session closes after 30 seconds without any client messageErrors are thrown from the loop:
RealtimeSTTErrorwhen the server ends the session or the connection is lost. It carrieserrorType(such asunsupported_audio),statusCode,requestIdand the WebSocketcloseCode.UnauthorizedError, orFishAudioErrorwith astatusCodesuch as 402 or 429, when the connection is refused.- The audio source's own error when the audio source throws.
An error the session survives arrives as an error event with recoverable: true instead.
convertRealtime runs in Node.js only, like the TTS WebSocket: browsers cannot set the Authorization header on a WebSocket.
import { FishAudioClient } from "fish-audio";
import { readFile } from "node:fs/promises";
const fishAudio = new FishAudioClient();
const title = "cloned-voice-name";
const audioFile = new File([await readFile("/path/to/your/audio/file.mp3")], "file.mp3");
const coverImageFile = new File([await readFile("/path/to/your/cover/image.png")], "image.png");
try {
const response = await fishAudio.voices.ivc.create({
title: title,
voices: [audioFile],
cover_image: coverImageFile,
});
console.log("Voice created:", {
id: response._id,
title: response.title,
state: response.state,
});
} catch (err) {
console.error("Create voice request failed:", err);
}fishAudio.voices.search()fishAudio.voices.get("your_model_id")fishAudio.voices.update("your_model_id", { title: "new_title" })fishAudio.voices.delete("your_model_id")fishAudio.user.get_api_credit()fishAudio.user.get_package()An HTTP request the API refuses throws a subclass of FishAudioError for its status, with the API's reason as the message (HTTP 404: Model not found) and statusCode, body and rawResponse:
| Status | Class |
|---|---|
| 400 | BadRequestError |
| 401 | UnauthorizedError |
| 402 | PaymentRequiredError |
| 403 | ForbiddenError |
| 404 | NotFoundError |
| 422 | UnprocessableEntityError |
| 425 | TooEarlyError |
| 429 | TooManyRequestsError |
| 500–599 | ServerError |
| any other | FishAudioError |
body is the JSON the API sent, the text when it is not JSON (such as a proxy's error page), or undefined when it could not be read (then cause is the read error). It is typed unknown: check it before reading a field such as body.request_id.
After HTTP 404: the message has the first of the JSON body's message, its detail, its validation entries as loc: msg (never their input), detail.message, detail.code, error and code; else the status phrase (Not Found). It is one line of at most 300 characters, with control characters escaped. The message comes from the API's JSON fields or is the status phrase; a non-JSON body is in error.body: a plain-text 404 gives HTTP 404: Not Found, and body keeps the whole response.
An HTTP request answered with 408, 429 or 5xx is retried twice before the error is thrown (maxRetries). An HTTP request that gets no response headers within its timeout (timeoutInSeconds, 240 s by default) throws FishAudioTimeoutError (name is "TimeoutError"). The timeout applies to each attempt and starts once the header functions have resolved. A request stopped by your abortSignal before a status arrives throws a FishAudioError with the message The user aborted a request; once a status has been received, the status error wins over a later abort, with the abort as cause. An error thrown by a header function is wrapped in a FishAudioError carrying its message.
Not every error is a FishAudioError. An invalid argument the SDK checks itself, such as a keyterms that is not an array, throws a plain TypeError before any request. The audio stream that textToSpeech.convert() returns is the response body: aborting it, or a connection lost while you read it, surfaces the error of the stream itself, which the runtime decides (for an abort, the runtime's own abort error).
instanceof does not hold between the package's CommonJS and ES module builds: an error thrown by one build (for example through a CommonJS dependency) is not an instance of the class imported from the other. statusCode is the check that works across that boundary.
A refused realtime speech-to-text connection throws a FishAudioError with statusCode, body and rawResponse, from the loop (BadRequestError, UnauthorizedError, ForbiddenError or NotFoundError for 400, 401, 403 and 404). An error status gets its message by the same rule as an HTTP call, read only from a body received whole; body holds at most the first 64 KiB. Any other answer, such as a 200 page or a redirect, gives The realtime connection was refused. HTTP 302: Found. A compressed refusal body is not decoded, so its message is the status phrase. A refused realtime text-to-speech connection gives the same error, as its ERROR event. When you contact support, include the trace id and the error code. Either can be absent.
import { FishAudioError, NotFoundError } from "fish-audio";
try {
await client.voices.get("voice-id");
} catch (err) {
if (err instanceof NotFoundError) {
// the voice does not exist
} else if (err instanceof FishAudioError) {
console.error(err.message, err.rawResponse?.headers.get("x-fish-trace-id"), err.rawResponse?.headers.get("x-fish-error-code"));
}
}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. Read it from the raw response of a call:
const { data: audio, rawResponse } = await fishAudio.textToSpeech
.convert({ text: "Hello!" })
.withRawResponse();
const traceId = rawResponse.headers.get("x-fish-trace-id"); // null if not sentspeechToText.convert() works the same way; its result has request_id when the API returns one. A realtime transcription stream has the handshake response as stream.rawResponse once the first event has arrived; it stays there after the session has ended or failed. On textToSpeech.convertRealtime(), a RealtimeTTSError carries it as error.rawResponse.
To continue your trace in the Fish Audio API, send a W3C traceparent header. Let exactly one thing add it to each request: with two traceparent headers the API starts a new trace.
With OpenTelemetry auto-instrumentation, there is nothing to do. Register @opentelemetry/instrumentation-undici (HTTP requests, which use fetch) and @opentelemetry/instrumentation-http (the WebSocket handshakes) before your application's imports, for example with node --import ./instrumentation.mjs. Do not also set traceparent yourself.
Without it, pass the header yourself. A function is called for each HTTP request and each WebSocket connection, so it can return the current trace:
const fishAudio = new FishAudioClient({
headers: { traceparent: () => currentTraceparent() },
});Or per call. A per-call header replaces the client's header written the same way, and null removes it; use the client's spelling of the name. A per-call Authorization replaces the API key, on the WebSocket handshakes too; there model is always the model the call chooses:
await fishAudio.textToSpeech.convert(request, "s3-pro", { headers: { traceparent } });
await fishAudio.textToSpeech.convertRealtime(request, textStream, "s3-pro", { headers: { traceparent } });
fishAudio.speechToText.convertRealtime({}, audio, { headers: { traceparent } });This project is licensed under the Apache-2.0 License - see the LICENSE file for details.