# JavaScript text-to-speech libraries

JavaScript text-to-speech libraries turn written text into spoken audio from Node.js or the browser. Most send the text or SSML markup to a cloud speech service that returns audio in a chosen voice. These libraries let voice agents, accessibility features, and audiobook tools speak text aloud.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [openai](#openai) | 223.6M | 11.3K | Nov 2026 | Apache-2.0 |
| [@elevenlabs/elevenlabs-js](#elevenlabs) | 5.7M | 454 | Nov 2026 | MIT |
| [@deepgram/sdk](#deepgram-sdk) | 5.3M | 286 | Nov 2026 | MIT |
| [@aws-sdk/client-polly](#amazon-polly) | 3.7M | 3.7K | Nov 2026 | Apache-2.0 |
| [microsoft-cognitiveservices-speech-sdk](#microsoft-cognitiveservices-speech-sdk) | 2.7M | 327 | Oct 2026 | MIT |
| [@google-cloud/text-to-speech](#cloud-text-to-speech) | 1.7M | 3.2K | Oct 2026 | Apache-2.0 |
| [kokoro-js](#kokoro) | 905.9K | 10.2K | May 2025 | Apache-2.0 |
| [@cartesia/cartesia-js](#cartesia-cartesia-js) | 534.3K | 134 | Nov 2026 | Apache-2.0 |

Downloads: npm, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[ElevenLabs](#elevenlabs) has the most monthly downloads among the speech-focused SDKs in this comparison, at 5.5M.

## Capabilities

| Library | Native text streaming | In-process synthesis |
| --- | --- | --- |
| [openai](#openai) | No | No |
| [@elevenlabs/elevenlabs-js](#elevenlabs) | No | No |
| [@deepgram/sdk](#deepgram-sdk) | Yes | No |
| [@aws-sdk/client-polly](#amazon-polly) | No | No |
| [microsoft-cognitiveservices-speech-sdk](#microsoft-cognitiveservices-speech-sdk) | Yes | No |
| [@google-cloud/text-to-speech](#cloud-text-to-speech) | Yes | No |
| [kokoro-js](#kokoro) | Yes | Yes |
| [@cartesia/cartesia-js](#cartesia-cartesia-js) | Yes | No |

## Libraries

### openai

[GitHub](https://github.com/openai/openai-node) · [npm](https://www.npmjs.com/package/openai) · [Docs](https://github.com/openai/openai-node/blob/main/README.md)

Provides the official TypeScript client for the OpenAI API.

- Downloads / mo: 223.6M
- Stars: 11.3K
- Last release: 7.60.0
- License: Apache-2.0
- Capabilities: [From the openai docs](https://github.com/openai/openai-node/blob/main/README.md)

```sh
npm install openai
```

**Mintplex-Labs/anything-llm** (68.4K stars)

[Mintplex-Labs/anything-llm](https://github.com/Mintplex-Labs/anything-llm) 

```javascript
async ttsBuffer(textInput) {
  try {
    const result = await this.openai.audio.speech.create({
      model: "tts-1",
      voice: this.voice,
      input: textInput,
    });
    return Buffer.from(await result.arrayBuffer());
  } catch (e) {
    console.error(e);
  }
  return null;
}

```

[server/utils/TextToSpeech/openAi/index.js](https://github.com/Mintplex-Labs/anything-llm/blob/2f6a451f55aca970311af2579088fe0c27af3ce8/server/utils/TextToSpeech/openAi/index.js#L12-L24) · [More projects using openai →](https://dashboard.exa.ai/playground/search?q=openai%20GitHub%20projects)

**Quickstart**

```javascript
import OpenAI from 'openai';

const client = new OpenAI();
const audio = await client.audio.speech.create({
  model: 'gpt-4o-mini-tts', voice: 'alloy', input: 'Hello, world!'
});
const bytes = await audio.arrayBuffer();

```

From [speech.d.ts](https://cdn.jsdelivr.net/npm/openai@7.60.0/resources/audio/speech.d.ts)

### @elevenlabs/elevenlabs-js

[GitHub](https://github.com/elevenlabs/elevenlabs-js) · [npm](https://www.npmjs.com/package/@elevenlabs/elevenlabs-js) · [Docs](https://github.com/elevenlabs/elevenlabs-js/blob/main/README.md)

Generates speech through ElevenLabs with streamed audio, voice selection, and surrounding-text context.

- Downloads / mo: 5.7M
- Stars: 454
- Last release: 2.79.0
- License: MIT
- Capabilities: [From the @elevenlabs/elevenlabs-js docs](https://github.com/elevenlabs/elevenlabs-js/blob/main/README.md)

**Strengths**

- **Streams generated audio.** Consume response audio while it arrives.
- **Connects neighboring speech clips.** Supply preceding text to improve continuity between generated clips.

**Watch out for**

- **Some formats need upgraded plans.** Higher-bitrate MP3 and some WAV outputs require eligible subscription tiers.
- **Playback needs local media tools.** Install MPV and ffmpeg when using the SDK’s play helper.

```sh
npm install @elevenlabs/elevenlabs-js
```

**TanStack/ai** (3.4K stars)

[TanStack/ai](https://github.com/TanStack/ai) 

```typescript
async generateSpeech(
  options: TTSOptions<ElevenLabsSpeechProviderOptions>,
): Promise<TTSResult> {
  const { logger } = options
  logger.request(
    `activity=generateSpeech provider=elevenlabs model=${this.model}`,
    { provider: 'elevenlabs', model: this.model },
  )
  try {
    const {
      outputFormat,
      voiceSettings,
      languageCode,
      seed,
      previousText,
      nextText,
      previousRequestIds,
      nextRequestIds,
      applyTextNormalization,
      applyLanguageTextNormalization,
      optimizeStreamingLatency,
      enableLogging,
    } = options.modelOptions ?? {}
    const effectiveOutputFormat =
      outputFormat ?? inferOutputFormatFromResponseFormat(options.format)
    const wrapAsWav = outputFormat == null && options.format === 'wav'
    const { format, contentType } = wrapAsWav
      ? { format: 'wav', contentType: 'audio/wav' }
      : parseOutputFormat(effectiveOutputFormat)
    const requestOptions = options.abortSignal
      ? { abortSignal: options.abortSignal }
      : {}
    // `format: 'wav'` asks ElevenLabs for pcm_44100 and wraps it here, on
    // every endpoint: the byte-stream pair hands back raw bytes, the
    // timestamped pair hands back the same bytes as base64.
    const encodeAudio = (buffer: ArrayBuffer) =>
      arrayBufferToBase64(wrapAsWav ? wrapPcmAsWav(buffer) : buffer)
    const encodeAudioBase64 = (audioBase64: string) =>
      wrapAsWav ? encodeAudio(base64ToArrayBuffer(audioBase64)) : audioBase64
    const base = {
      modelId: this.model,
      ...(effectiveOutputFormat
        ? { outputFormat: effectiveOutputFormat }
        : {}),
      ...(languageCode ? { languageCode } : {}),
      ...(seed != null ? { seed } : {}),
      ...(applyTextNormalization ? { applyTextNormalization } : {}),
    }

    // Four endpoints, picked by (turns?, timestamps?). The dialogue pair
    // takes `inputs` instead of a voice id in the path, and the timestamped
    // pair returns JSON (base64 audio + alignment) instead of a byte stream.
    if (options.turns) {
      const inputs = options.turns.map((turn) => ({
        text: turn.text,
        voiceId: turn.voice,
      }))
      const dialogue = {
        ...base,
        inputs,
        ...(voiceSettings?.stability != null
          ? { settings: { stability: voiceSettings.stability } }
          : {}),
      }

      if (options.timestamps) {
        const response =
          await this.client.textToDialogue.convertWithTimestamps(
            dialogue,
            requestOptions,
          )
        return {
          id: generateId(this.name),
          model: this.model,
          audio: encodeAudioBase64(response.audioBase64),
          format,
          contentType,
          ...toAlignmentFields(response.alignment, response.voiceSegments),
        }
      }

      const stream = await this.client.textToDialogue.convert(
        dialogue,
        requestOptions,
      )
      return {
        id: generateId(this.name),
        model: this.model,
        audio: encodeAudio(await readStreamToArrayBuffer(stream)),
        format,
        contentType,
      }
    }

    const voiceId = options.voice ?? options.modelOptions?.voiceId
    if (!voiceId) {
      throw new Error(
        'ElevenLabs TTS requires a voice. Pass `voice` on generateSpeech() or `voiceId` in modelOptions.',
      )
    }
    const single = {
      ...base,
      text: options.text,
      ...(voiceSettings
        ? { voiceSettings: mapVoiceSettings(voiceSettings, options.speed) }
        : options.speed != null
          ? { voiceSettings: { speed: options.speed } }
          : {}),
      ...(previousText ? { previousText } : {}),
      ...(nextText ? { nextText } : {}),
      ...(previousRequestIds ? { previousRequestIds } : {}),
      ...(nextRequestIds ? { nextRequestIds } : {}),
      ...(applyLanguageTextNormalization != null
        ? { applyLanguageTextNormalization }
        : {}),
      ...(enableLogging != null ? { enableLogging } : {}),
    }

    if (options.timestamps) {
      const response = await this.client.textToSpeech.convertWithTimestamps(
        voiceId,
        single,
        requestOptions,
      )
      return {
        id: generateId(this.name),
        model: this.model,
        audio: encodeAudioBase64(response.audioBase64),
        format,
        contentType,
        ...toAlignmentFields(response.alignment, undefined),
      }
    }

    const stream = await this.client.textToSpeech.convert(
      voiceId,
      {
        ...single,
        ...(optimizeStreamingLatency != null
          ? { optimizeStreamingLatency }
          : {}),
      },
      requestOptions,
    )

    return {
      id: generateId(this.name),
      model: this.model,
      audio: encodeAudio(await readStreamToArrayBuffer(stream)),
      format,
      contentType,
    }
  } catch (error) {
    logger.errors('elevenlabs.generateSpeech fatal', {
      error,
      source: 'elevenlabs.generateSpeech',
    })
    throw error
  }
}

```

[packages/ai-elevenlabs/src/adapters/speech.ts](https://github.com/TanStack/ai/blob/c7f8dfd58129c5538090fc9ab8c91cd93c6125ab/packages/ai-elevenlabs/src/adapters/speech.ts#L111-L270) · [More projects using @elevenlabs/elevenlabs-js →](https://dashboard.exa.ai/playground/search?q=JavaScript%20applications%20using%20%40elevenlabs/elevenlabs-js%20to%20generate%20spoken%20audio%20from%20text&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```typescript
import { ElevenLabsClient } from '@elevenlabs/elevenlabs-js';

const client = new ElevenLabsClient();
const audio = await client.textToSpeech.convert('JBFqnCBsd6RMkjVDRZzb', {
  text: 'Hello, world!'
});

```

From [README.md](https://github.com/elevenlabs/elevenlabs-js/blob/main/README.md)

### @deepgram/sdk

[GitHub](https://github.com/deepgram/deepgram-js-sdk) · [npm](https://www.npmjs.com/package/@deepgram/sdk) · [Docs](https://github.com/deepgram/deepgram-js-sdk/blob/main/README.md)

Provides the official SDK for the Deepgram speech recognition, text-to-speech, and language understanding APIs.

- Downloads / mo: 5.3M
- Stars: 286
- Last release: 5.20.0
- License: MIT
- Capabilities: [From the @deepgram/sdk docs](https://github.com/deepgram/deepgram-js-sdk/blob/main/README.md)

```sh
npm install @deepgram/sdk
```

**Quickstart**

```javascript
import { DeepgramClient } from '@deepgram/sdk';

const client = new DeepgramClient();
const audio = await client.speak.v1.audio.generate({
  text: 'Hello, world!', model: 'aura-2-thalia-en'
});

```

From [README.md](https://github.com/deepgram/deepgram-js-sdk/blob/main/README.md) · [Find projects using @deepgram/sdk →](https://dashboard.exa.ai/playground/search?q=%40deepgram/sdk%20GitHub%20projects)

### @aws-sdk/client-polly

[GitHub](https://github.com/aws/aws-sdk-js-v3) · [npm](https://www.npmjs.com/package/@aws-sdk/client-polly) · [Docs](https://github.com/aws/aws-sdk-js-v3/blob/main/README.md)

Sends plain text or SSML to Amazon Polly and receives encoded speech or speech metadata.

- Downloads / mo: 3.7M
- Stars: 3.7K
- Last release: 3.1172.0
- License: Apache-2.0
- Capabilities: [From the @aws-sdk/client-polly docs](https://github.com/aws/aws-sdk-js-v3/blob/main/README.md)

**Strengths**

- **Accepts marked-up speech input.** Send plain text or SSML to control synthesis.
- **Returns word timing metadata.** Request speech marks to locate words and sentences in generated audio.

**Watch out for**

- **Timing metadata replaces audio.** Request synthesized audio separately when speech marks are also needed.
- **SSML support varies by voice.** Check tag availability before switching synthesis voices.

```sh
npm install @aws-sdk/client-polly
```

**aws-amplify/amplify-js** (9.6K stars)

[aws-amplify/amplify-js](https://github.com/aws-amplify/amplify-js) 

```typescript
protected async convertTextToSpeech(
	input: TextToSpeechInput,
): Promise<TextToSpeechOutput> {
	const { credentials } = await this._resolveCtx().fetchAuthSession();
	assertValidationError(
		!!credentials,
		PredictionsValidationErrorCode.NoCredentials,
	);
	assertValidationError(
		!!input.textToSpeech?.source,
		PredictionsValidationErrorCode.NoSource,
	);

	const { speechGenerator } =
		this._resolveCtx().resourcesConfig.Predictions?.convert ?? {};
	assertValidationError(
		!!speechGenerator?.region,
		PredictionsValidationErrorCode.NoRegion,
	);

	const { defaults = {}, region } = speechGenerator;

	const { voiceId: defaultVoiceId } = defaults;
	const voiceId = input.textToSpeech?.voiceId ?? defaultVoiceId;
	assertValidationError(!!voiceId, PredictionsValidationErrorCode.NoVoiceId);

	this.pollyClient = new PollyClient({
		region,
		credentials,
		customUserAgent: getAmplifyUserAgentObject({
			category: Category.Predictions,
			action: PredictionsAction.Convert,
		}),
	});
	const synthesizeSpeechCommand = new SynthesizeSpeechCommand({
		OutputFormat: 'mp3',
		Text: input.textToSpeech?.source?.text,
		VoiceId: voiceId as SynthesizeSpeechInput['VoiceId'],
		TextType: 'text',
		SampleRate: '24000',
	});
	const data = await this.pollyClient.send(synthesizeSpeechCommand);
	const response = new Response(data.AudioStream as ReadableStream);
	const arrayBuffer = await response.arrayBuffer();
	const blob = new Blob([arrayBuffer], {
		type: data.ContentType,
	});
	const url = URL.createObjectURL(blob);

	return {
		speech: { url },
		audioStream: arrayBuffer,
		text: input.textToSpeech?.source?.text,
	} as TextToSpeechOutput;
}

```

[packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts](https://github.com/aws-amplify/amplify-js/blob/9e01896b2f4346c10e980afe7bcd1d68207f7502/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts#L159-L213) · [More projects using @aws-sdk/client-polly →](https://dashboard.exa.ai/playground/search?q=JavaScript%20applications%20using%20%40aws-sdk/client-polly%20to%20generate%20spoken%20audio%20from%20text&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```typescript
import { PollyClient, SynthesizeSpeechCommand } from '@aws-sdk/client-polly';

const client = new PollyClient({ region: 'us-east-1' });
const result = await client.send(new SynthesizeSpeechCommand({
  Text: 'Hello, world!', VoiceId: 'Joanna', OutputFormat: 'mp3'
}));

```

From [javascript_polly_code_examples.html](https://cdn.jsdelivr.net/npm/@aws-sdk/client-polly@3.1172.0/dist-types/commands/SynthesizeSpeechCommand.d.ts)

### microsoft-cognitiveservices-speech-sdk

[GitHub](https://github.com/microsoft/cognitive-services-speech-sdk-js) · [npm](https://www.npmjs.com/package/microsoft-cognitiveservices-speech-sdk) · [Docs](https://github.com/microsoft/cognitive-services-speech-sdk-js/blob/master/README.md)

Provides the Microsoft Speech SDK for JavaScript.

- Downloads / mo: 2.7M
- Stars: 327
- Last release: 1.53.0
- License: MIT
- Capabilities: [From the microsoft-cognitiveservices-speech-sdk docs](https://github.com/microsoft/cognitive-services-speech-sdk-js/blob/master/README.md)

```sh
npm install microsoft-cognitiveservices-speech-sdk
```

**Azure-Samples/cognitive-services-speech-sdk** (3.5K stars)

[Azure-Samples/cognitive-services-speech-sdk](https://github.com/Azure-Samples/cognitive-services-speech-sdk) 

```javascript
function () {
        resultsDiv.innerHTML = "";
        eventsDiv.innerHTML = "";
        wordBoundaryList = [];
        synthesisText = document.getElementById("synthesisText");

        // if we got an authorization token, use the token. Otherwise use the provided subscription key
        var speechConfig;
        if (subscriptionKey.value === "" || subscriptionKey.value === "subscription") {
          alert("Please enter your Microsoft Cognitive Services Speech subscription key!");
          return;
        }
        speechConfig = SpeechSDK.SpeechConfig.fromSubscription(subscriptionKey.value, regionOptions.value);

        speechConfig.speechSynthesisVoiceName = voiceOptions.value;
        speechConfig.speechSynthesisOutputFormat = formatOptions.value;

        player = new SpeechSDK.SpeakerAudioDestination();
        player.onAudioStart = function(_) {
          window.console.log("playback started");
          setTimeout(function(){ $("svg path :first-child").each( function(i) {this.beginElement();}); }, 0.5);
        }
        player.onAudioEnd = function (_) {
          window.console.log("playback finished");
          eventsDiv.innerHTML += "playback finished" + "\r\n";
          startSynthesisAsyncButton.disabled = false;
          downloadButton.disabled = false;
          pauseButton.disabled = true;
          resumeButton.disabled = true;
          wordBoundaryList = [];
        };

        var audioConfig  = SpeechSDK.AudioConfig.fromSpeakerOutput(player);

        synthesizer = new SpeechSDK.SpeechSynthesizer(speechConfig, audioConfig);

        // The event synthesizing signals that a synthesized audio chunk is received.
        // You will receive one or more synthesizing events as a speech phrase is synthesized.
        // You can use this callback to streaming receive the synthesized audio.
        synthesizer.synthesizing = function (s, e) {
          window.console.log(e);
          eventsDiv.innerHTML += "(synthesizing) Reason: " + SpeechSDK.ResultReason[e.result.reason] +
                  "Audio chunk length: " + e.result.audioData.byteLength + "\r\n";
        };

        // The synthesis started event signals that the synthesis is started.
        synthesizer.synthesisStarted = function (s, e) {
          window.console.log(e);
          eventsDiv.innerHTML += "(synthesis started)" + "\r\n";
          pauseButton.disabled = false;
        };

        // The event synthesis completed signals that the synthesis is completed.
        synthesizer.synthesisCompleted = function (s, e) {
          console.log(e);
          eventsDiv.innerHTML += "(synthesized)  Reason: " + SpeechSDK.ResultReason[e.result.reason] +
                  " Audio length: " + e.result.audioData.byteLength + "\r\n";
        };

        // The event signals that the service has stopped processing speech.
        // This can happen when an error is encountered.
        synthesizer.SynthesisCanceled = function (s, e) {
          const cancellationDetails = SpeechSDK.CancellationDetails.fromResult(e.result);
          let str = "(cancel) Reason: " + SpeechSDK.CancellationReason[cancellationDetails.reason];
          if (cancellationDetails.reason === SpeechSDK.CancellationReason.Error) {
            str += ": " + e.result.errorDetails;
          }
          window.console.log(e);
          eventsDiv.innerHTML += str + "\r\n";
          startSynthesisAsyncButton.disabled = false;
          downloadButton.disabled = false;
          pauseButton.disabled = true;
          resumeButton.disabled = true;
        };

        // This event signals that word boundary is received. This indicates the audio boundary of each word.
        // The unit of e.audioOffset is tick (1 tick = 100 nanoseconds), divide by 10,000 to convert to milliseconds.
        synthesizer.wordBoundary = function (s, e) {
          window.console.log(e);
          eventsDiv.innerHTML += "(WordBoundary), Text: " + e.text + ", Audio offset: " + e.audioOffset / 10000 + "ms." + "\r\n";
          wordBoundaryList.push(e);
        };

        synthesizer.visemeReceived = function (s, e) {
          window.console.log(e);
          eventsDiv.innerHTML += "(Viseme), Audio offset: " + e.audioOffset / 10000 + "ms. Viseme ID: " + e.visemeId + '\n';
          talkingHeadDiv.innerHTML = e.animation.replaceAll("begin=\"0.5s\"", "begin=\"indefinite\"");
          $("svg").width('500px').height('500px');
        }

        synthesizer.bookmarkReached = function (s, e) {
          window.console.log(e);
          eventsDiv.innerHTML +=  "(Bookmark reached), Audio offset: " + e.audioOffset / 10000 + "ms. Bookmark text: " + e.text + '\n';
        }

        const complete_cb = function (result) {
          if (result.reason === SpeechSDK.ResultReason.SynthesizingAudioCompleted) {
            resultsDiv.innerHTML += "synthesis finished";
          } else if (result.reason === SpeechSDK.ResultReason.Canceled) {
            resultsDiv.innerHTML += "synthesis failed. Error detail: " + result.errorDetails;
          }
          window.console.log(result);
          synthesizer.close();
          synthesizer = undefined;
        };
        const err_cb = function (err) {
          startSynthesisAsyncButton.disabled = false;
          downloadButton.disabled = false;
          phraseDiv.innerHTML += err;
          window.console.log(err);
          synthesizer.close();
          synthesizer = undefined;
        };

        if (!synthesisText.value) {
          alert("Please enter synthesis content.");
          return;
        }

        startSynthesisAsyncButton.disabled = true;
        downloadButton.disabled = true;

        if (isSsml.checked) {
          synthesizer.speakSsmlAsync(synthesisText.value,
                  complete_cb,
                  err_cb);
        } else {
          synthesizer.speakTextAsync(synthesisText.value,
                  complete_cb,
                  err_cb);
        }
      }

```

[samples/js/browser/synthesis.html](https://github.com/Azure-Samples/cognitive-services-speech-sdk/blob/528cbfad1c14d5a546e5e9bc5a34e6a84478db7e/samples/js/browser/synthesis.html#L320-L451) · [More projects using microsoft-cognitiveservices-speech-sdk →](https://dashboard.exa.ai/playground/search?q=microsoft-cognitiveservices-speech-sdk%20GitHub%20projects)

**Quickstart**

```javascript
import * as speech from 'microsoft-cognitiveservices-speech-sdk';

const config = speech.SpeechConfig.fromSubscription(
  process.env.SPEECH_KEY, process.env.SPEECH_REGION
);
const synthesizer = new speech.SpeechSynthesizer(config, null);
try {
  const result = await new Promise((resolve, reject) => {
    synthesizer.speakTextAsync('Hello, world!', resolve, reject);
  });
  console.log(result.audioData.byteLength);
} finally {
  synthesizer.close();
}

```

From [SpeechSynthesizer.d.ts](https://cdn.jsdelivr.net/npm/microsoft-cognitiveservices-speech-sdk@1.53.0/distrib/lib/src/sdk/SpeechSynthesizer.d.ts)

### @google-cloud/text-to-speech

[GitHub](https://github.com/googleapis/google-cloud-node) · [npm](https://www.npmjs.com/package/@google-cloud/text-to-speech) · [Docs](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-texttospeech/README.md)

Synthesizes speech through Google Cloud, with SSML controls and compatible bidirectional streaming voices.

- Downloads / mo: 1.7M
- Stars: 3.2K
- Last release: 7.2.0
- License: Apache-2.0
- Capabilities: [From the @google-cloud/text-to-speech docs](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-texttospeech/README.md)

**Strengths**

- **Controls pauses through SSML.** Mark pauses and spoken formatting in the synthesis request.
- **Receives audio while sending text.** Bidirectional streaming accepts more text before the full input is ready.

**Watch out for**

- **Streaming needs compatible voices.** Use Chirp 3: HD voices for bidirectional streaming.
- **Requests allow 5,000 input bytes.** Split longer input; some characters require multiple bytes.

```sh
npm install @google-cloud/text-to-speech
```

**GoogleCloudPlatform/nodejs-docs-samples** (3.0K stars)

[GoogleCloudPlatform/nodejs-docs-samples](https://github.com/GoogleCloudPlatform/nodejs-docs-samples) 

```typescript
async function synthesizeSsml(ssml, outputFile) {
  // [START tts_synthesize_ssml]
  const textToSpeech = require('@google-cloud/text-to-speech');
  const fs = require('fs');
  const util = require('util');

  const client = new textToSpeech.TextToSpeechClient();

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const ssml = '<speak>Hello there.</speak>';
  // const outputFile = 'Local path to save audio file to, e.g. output.mp3';

  const request = {
    input: {ssml: ssml},
    voice: {languageCode: 'en-US', ssmlGender: 'FEMALE'},
    audioConfig: {audioEncoding: 'MP3'},
  };

  const [response] = await client.synthesizeSpeech(request);
  const writeFile = util.promisify(fs.writeFile);
  await writeFile(outputFile, response.audioContent, 'binary');
  console.log(`Audio content written to file: ${outputFile}`);
  // [END tts_synthesize_ssml]
}

```

[texttospeech/synthesize.js](https://github.com/GoogleCloudPlatform/nodejs-docs-samples/blob/7d399e2b93deac11a75e781b0525580d8a7cceec/texttospeech/synthesize.js#L42-L67) · [More projects using @google-cloud/text-to-speech →](https://dashboard.exa.ai/playground/search?q=JavaScript%20applications%20using%20%40google-cloud/text-to-speech%20to%20generate%20spoken%20audio%20from%20text&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```typescript
const { TextToSpeechClient } = require('@google-cloud/text-to-speech');

(async () => {
  const client = new TextToSpeechClient();
  const [result] = await client.synthesizeSpeech({
    input: { text: 'Hello, world!' },
    voice: { languageCode: 'en-US', ssmlGender: 'NEUTRAL' },
    audioConfig: { audioEncoding: 'MP3' }
  });
})();

```

From [quickstart.js](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-texttospeech/README.md)

### kokoro-js

[GitHub](https://github.com/hexgrad/kokoro) · [npm](https://www.npmjs.com/package/kokoro-js) · [Docs](https://github.com/hexgrad/kokoro/blob/dfb907a02bba8152ca444717ca5d78747ccb4bec/kokoro.js/README.md)

Runs speech synthesis locally through Transformers.js, with voice selection and sentence-level streaming.

- Downloads / mo: 905.9K
- Stars: 10.2K
- Last release: 1.2.1
- License: Apache-2.0
- Capabilities: [From the kokoro-js docs](https://github.com/hexgrad/kokoro/blob/dfb907a02bba8152ca444717ca5d78747ccb4bec/kokoro.js/README.md)

**Strengths**

- **Runs locally in the browser.** Synthesize speech locally after the required model assets load.
- **Accepts text incrementally.** Push new text through TextSplitterStream as it becomes available.

**Watch out for**

- **Long chunks are truncated.** Split long input into smaller chunks before synthesis.
- **Needs model assets before synthesis.** Load the selected model before generating speech.

```sh
npm install kokoro-js
```

**MartinDelophy/ai-video-editor** (987 stars)

[MartinDelophy/ai-video-editor](https://github.com/MartinDelophy/ai-video-editor) 

```typescript
export async function predictKokoroVoice(input, onProgress) {
  const tts = await loadRuntime(onProgress);
  onProgress?.({ backend: "wasm", progress: 92 });
  // Let React paint the phase change before main-thread WASM inference starts.
  // Otherwise the last download label remains visible throughout generation.
  await new Promise((resolve) => {
    if (globalThis.requestAnimationFrame) requestAnimationFrame(() => resolve());
    else setTimeout(resolve, 0);
  });

  // kokoro-js currently hard-codes its upstream voice-style URL. Intercept
  // only that one request so every runtime voice artifact comes from the
  // owned, immutable provider mirrors while retaining kokoro-js's cache key.
  const upstreamUrl = `${UPSTREAM_VOICE_PREFIX}${input.voiceId}.bin`;
  const originalFetch = globalThis.fetch;
  const mirroredFetch = (resource, init) => {
    const requestUrl = typeof resource === "string" ? resource : resource?.url;
    return requestUrl === upstreamUrl
      ? fetchOwnedVoiceStyle(input.voiceId, originalFetch, init)
      : originalFetch(resource, init);
  };
  globalThis.fetch = mirroredFetch;
  try {
    const audio = await tts.generate(input.text, { voice: input.voiceId, speed: input.speed });
    return audio.toBlob();
  } finally {
    if (globalThis.fetch === mirroredFetch) globalThis.fetch = originalFetch;
  }
}

```

[src/lib/kokoroVoiceRuntime.js](https://github.com/MartinDelophy/ai-video-editor/blob/6348fec70e87de7a3a9217fb3e772ed4b3c4713e/src/lib/kokoroVoiceRuntime.js#L90-L118) · [More projects using kokoro-js →](https://dashboard.exa.ai/playground/search?q=JavaScript%20applications%20using%20kokoro-js%20to%20generate%20spoken%20audio%20from%20text&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```typescript
import { KokoroTTS } from 'kokoro-js';

const tts = await KokoroTTS.from_pretrained(
  'onnx-community/Kokoro-82M-v1.0-ONNX', { dtype: 'q8', device: 'wasm' }
);
const audio = await tts.generate('Hello, world!', { voice: 'af_heart' });

```

From [README.md](https://github.com/hexgrad/kokoro/blob/dfb907a02bba8152ca444717ca5d78747ccb4bec/kokoro.js/README.md)

### @cartesia/cartesia-js

[GitHub](https://github.com/cartesia-ai/cartesia-js) · [npm](https://www.npmjs.com/package/@cartesia/cartesia-js) · [Docs](https://github.com/cartesia-ai/cartesia-js/blob/main/README.md)

Provides the official TypeScript client for the Cartesia API.

- Downloads / mo: 534.3K
- Stars: 134
- Last release: 5.1.0
- License: Apache-2.0
- Capabilities: [From the @cartesia/cartesia-js docs](https://github.com/cartesia-ai/cartesia-js/blob/main/README.md)

```sh
npm install @cartesia/cartesia-js
```

**sonichi/sutando** (411 stars)

[sonichi/sutando](https://github.com/sonichi/sutando) 

```javascript
export async function generateSpeech(
	text: string,
	options: { outputPath?: string; category?: string; label?: string } = {},
): Promise<string> {
	if (!getCartesiaApiKey()) throw new Error('CARTESIA_API_KEY not set');
	if (!text.trim()) throw new Error('Empty text');

	// Organize: results/audio/{category}/{label}-{timestamp}.wav
	const category = options.category || 'general';
	const label = options.label || 'tts';
	const outDir = join(getWorkspace(), 'results', 'audio', category);
	mkdirSync(outDir, { recursive: true });
	const outPath = options.outputPath || join(outDir, `${label}-${Date.now()}.wav`);

	const client = new Cartesia({ apiKey: getCartesiaApiKey() });
	const ws = await client.tts.websocket();
	try {
		const ctx = ws.context({
			model_id: 'sonic-3',
			voice: { mode: 'id', id: getCartesiaVoiceId() },
			output_format: {
				container: 'raw',
				encoding: 'pcm_s16le',
				sample_rate: SAMPLE_RATE,
			},
		});

		// Push text in sentence chunks for natural prosody
		const sentences = splitSentences(text);
		for (const s of sentences) {
			await ctx.push({ transcript: s.trim() + ' ' });
		}
		await ctx.no_more_inputs();

		const chunks: Buffer[] = [];
		for await (const event of ctx.receive()) {
			if (event.type === 'chunk' && event.audio) {
				chunks.push(Buffer.isBuffer(event.audio) ? event.audio : Buffer.from(event.audio));
			} else if (event.type === 'done') {
				break;
			}
		}

		// Write WAV with header
		const pcm = Buffer.concat(chunks);
		const header = createWavHeader(pcm.length, SAMPLE_RATE, CHANNELS, BIT_DEPTH);
		writeFileSync(outPath, Buffer.concat([header, pcm]));
		return outPath;
	} finally {
		ws.close();
	}
}

```

[src/cartesia-tts.ts](https://github.com/sonichi/sutando/blob/191a397a877c5e14dcd2ce13741a44e97d40c97d/src/cartesia-tts.ts#L58-L109) · [More projects using @cartesia/cartesia-js →](https://dashboard.exa.ai/playground/search?q=%40cartesia/cartesia-js%20GitHub%20projects)

**Quickstart**

```javascript
import Cartesia from '@cartesia/cartesia-js';

const client = new Cartesia({ apiKey: process.env.CARTESIA_API_KEY });
const response = await client.tts.generate({
  model_id: 'sonic-latest',
  transcript: 'Hello, world!',
  voice: 'f786b574-daa5-4673-aa0c-cbe3e8534c02',
  output_format: { container: 'wav', encoding: 'pcm_f32le', sample_rate: 44100 }
});
const audio = await response.blob();

```

From [README.md](https://github.com/cartesia-ai/cartesia-js/blob/main/README.md)

## FAQ

### Which JavaScript text-to-speech library should I use?

[ElevenLabs](#elevenlabs) suits apps that need streamed, expressive voices. [Amazon Polly](#amazon-polly) and [Google Cloud Text-to-Speech](#cloud-text-to-speech) suit apps that already run on those clouds and want SSML control. [Kokoro](#kokoro) suits apps that must synthesize speech locally.

### What is Amazon Polly?

[Amazon Polly](#amazon-polly) is the AWS text-to-speech service. Its JavaScript client sends plain text or SSML and receives encoded speech or speech metadata.

### What is Kokoro TTS?

Kokoro is an open-weight text-to-speech model. [kokoro-js](#kokoro) runs it locally through Transformers.js with voice selection and sentence-level streaming.

### What are the alternatives to ElevenLabs?

[Amazon Polly](#amazon-polly), [Google Cloud Text-to-Speech](#cloud-text-to-speech), [Deepgram](#deepgram-sdk), and [Cartesia](#cartesia-cartesia-js) offer hosted speech APIs with JavaScript SDKs. [Kokoro](#kokoro) runs speech synthesis locally with no API account.

### How does Azure text to speech work in JavaScript?

Azure text to speech runs through the [Microsoft Speech SDK](#microsoft-cognitiveservices-speech-sdk) for JavaScript. The same SDK also covers speech recognition.

### How does OpenAI text to speech work in JavaScript?

The [OpenAI](#openai) TypeScript library calls the OpenAI speech endpoint. The endpoint returns audio of the input text in a chosen voice.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best JavaScript text-to-speech libraries Google Cloud Amazon Polly ElevenLabs Kokoro.js code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
