### Install kokoro-js Library
Source: https://www.npmjs.com/package/kokoro-js/index_activetab=readme
Installs the kokoro-js library using npm. This is the first step before using the library's functionalities.
```bash
npm i kokoro-js
```
--------------------------------
### Browser Text-to-Speech with Kokoro JS
Source: https://context7.com/context7/npmjs_package_kokoro-js/llms.txt
This snippet shows a full HTML page setup for browser-based text-to-speech using Kokoro JS. It includes a text area, voice selection dropdown, a button to generate speech, and an audio player. The model is initialized for WebAssembly (wasm) execution, and generated audio is played directly in the browser. Dependencies include the Kokoro JS library loaded via CDN.
```html
Kokoro TTS Demo
Text to Speech
```
--------------------------------
### Select and Generate Speech with Kokoro-JS
Source: https://context7.com/context7/npmjs_package_kokoro-js/llms.txt
This snippet shows how to initialize Kokoro-JS, list available voices, filter voices by quality and accent, and generate audio files using specific voices. It demonstrates generating both high-quality American English and British English speech.
```javascript
import { KokoroTTS } from "kokoro-js";
const tts = await KokoroTTS.from_pretrained("onnx-community/Kokoro-82M-v1.0-ONNX", {
dtype: "q8",
device: "wasm",
});
// List all voices
const allVoices = tts.list_voices();
console.log("Total voices available:", allVoices.length);
// Top-quality female voices (Grade A or A-)
const topFemaleVoices = ["af_heart", "af_bella"]; // af_heart (A), af_bella (A-)
// Top-quality male voices (Grade C+ or higher)
const goodMaleVoices = ["am_fenrir", "am_michael", "am_puck"]; // All C+ grade
// British English voices
const britishFemaleVoices = ["bf_emma", "bf_isabella"]; // bf_emma (B-, highest British female)
const britishMaleVoices = ["bm_george", "bm_fable"]; // Both C grade
// Example: Generate with highest quality voice
const audio = await tts.generate("This is a test of the highest quality voice.", {
voice: "af_heart", // Grade A voice
});
audio.save("high_quality.wav");
// Example: Generate with British accent
const audioBritish = await tts.generate("Cheerio, this is British English.", {
voice: "bf_emma", // Best British female voice
});
audioBritish.save("british_accent.wav");
```
--------------------------------
### Node.js Server-Side Speech Generation with Kokoro JS
Source: https://context7.com/context7/npmjs_package_kokoro-js/llms.txt
This Node.js script demonstrates server-side speech generation using Kokoro JS, saving audio output to files. It initializes the model for CPU execution and is suitable for batch processing tasks. The function takes an array of texts and an output directory, generating a WAV file for each input text. Dependencies include 'kokoro-js', 'fs/promises', and 'path'.
```javascript
import { KokoroTTS } from "kokoro-js";
import fs from "fs/promises";
import path from "path";
async function generateSpeechFiles(texts, outputDir) {
// Initialize model for CPU execution
const tts = await KokoroTTS.from_pretrained("onnx-community/Kokoro-82M-v1.0-ONNX", {
dtype: "q8",
device: "cpu", // Use CPU for Node.js
});
// Create output directory
await fs.mkdir(outputDir, { recursive: true });
// Generate audio for each text
const results = [];
for (let i = 0; i < texts.length; i++) {
const text = texts[i];
console.log(`Generating audio ${i + 1}/${texts.length}: "${text.substring(0, 50)}"...`);
const audio = await tts.generate(text, {
voice: "af_bella", // High-quality female voice (A- grade)
});
const filename = `speech_${i.toString().padStart(3, "0")}.wav`;
const filepath = path.join(outputDir, filename);
audio.save(filepath);
results.push({ text, filename, filepath });
}
console.log(`Generated ${results.length} audio files in ${outputDir}`);
return results;
}
// Example usage
const sampleTexts = [
"Welcome to our automated notification system.",
"Your order has been confirmed and will ship within 24 hours.",
"Thank you for your patience. A representative will be with you shortly.",
];
generateSpeechFiles(sampleTexts, "./output/audio")
.then(results => {
console.log("Results:", results);
})
.catch(error => {
console.error("Error:", error);
process.exit(1);
});
```
--------------------------------
### Load Kokoro TTS Model (JavaScript)
Source: https://context7.com/context7/npmjs_package_kokoro-js/llms.txt
Loads the Kokoro TTS model for text-to-speech synthesis. It allows configuration of data type (precision) and execution device (WASM, WebGPU, CPU). The model_id specifies the model to load, and the dtype and device options control performance and quality trade-offs. Successful loading is indicated by a console log.
```javascript
import { KokoroTTS } from "kokoro-js";
// Load model with quantized weights for faster performance
const model_id = "onnx-community/Kokoro-82M-v1.0-ONNX";
const tts = await KokoroTTS.from_pretrained(model_id, {
dtype: "q8", // Options: "fp32" (highest quality), "fp16", "q8" (balanced), "q4" (fastest), "q4f16"
device: "wasm", // Options: "wasm" (universal), "webgpu" (GPU-accelerated), "cpu" (Node.js)
});
// For WebGPU acceleration (browser only), use fp32 for best results
const ttsGPU = await KokoroTTS.from_pretrained(model_id, {
dtype: "fp32",
device: "webgpu",
});
console.log("Model loaded successfully");
```
--------------------------------
### Stream Audio Generation (JavaScript)
Source: https://context7.com/context7/npmjs_package_kokoro-js/llms.txt
Enables real-time audio generation by streaming audio output as text becomes available. This is useful for LLM integration and progressive rendering. It uses `TextSplitterStream` to process text chunks and `tts.stream()` to generate audio, which is then consumed asynchronously and can be saved as WAV files.
```javascript
import { KokoroTTS, TextSplitterStream } from "kokoro-js";
const model_id = "onnx-community/Kokoro-82M-v1.0-ONNX";
const tts = await KokoroTTS.from_pretrained(model_id, {
dtype: "fp32",
device: "webgpu",
});
// Set up the text splitter and audio stream
const splitter = new TextSplitterStream();
const stream = tts.stream(splitter);
// Consume the audio stream asynchronously
(async () => {
let i = 0;
for await (const { text, phonemes, audio } of stream) {
console.log({ text, phonemes });
audio.save(`audio-${i++}.wav`);
}
console.log(`Generated ${i} audio chunks`);
})();
// Simulate streaming text from an LLM word by word
const text = "Kokoro is an open-weight TTS model with 82 million parameters. Despite its lightweight architecture, it delivers comparable quality to larger models while being significantly faster and more cost-efficient. With Apache-licensed weights, Kokoro can be deployed anywhere from production environments to personal projects. It can even run 100% locally in your browser, powered by Transformers.js!";
const tokens = text.match(/\s*\S+/g);
for (const token of tokens) {
splitter.push(token);
await new Promise((resolve) => setTimeout(resolve, 10));
}
// Signal end of text stream
splitter.close();
// Alternative: flush without closing to keep stream open
// splitter.flush();
```
--------------------------------
### Generate Speech with Kokoro TTS (JavaScript)
Source: https://www.npmjs.com/package/kokoro-js/index
Demonstrates how to initialize the KokoroTTS model and generate speech from a given text. It specifies model ID, data type, and device for execution. The generated audio can be saved as a WAV file.
```javascript
import { KokoroTTS } from "kokoro-js";
const model_id = "onnx-community/Kokoro-82M-v1.0-ONNX";
const tts = await KokoroTTS.from_pretrained(model_id, {
dtype: "q8", // Options: "fp32", "fp16", "q8", "q4", "q4f16"
device: "wasm", // Options: "wasm", "webgpu" (web) or "cpu" (node). If using "webgpu", we recommend using dtype="fp32".
});
const text = "Life is like a box of chocolates. You never know what you're gonna get.";
const audio = await tts.generate(text, {
// Use `tts.list_voices()` to list all available voices
voice: "af_heart",
});
audio.save("audio.wav");
```
--------------------------------
### Generate Speech from Text (JavaScript)
Source: https://context7.com/context7/npmjs_package_kokoro-js/llms.txt
Converts input text into audio using the loaded Kokoro TTS model. It allows specifying a voice and outputs the audio, which can then be saved to a WAV file. The `list_voices()` method can be used to retrieve all available voice identifiers.
```javascript
import { KokoroTTS } from "kokoro-js";
const model_id = "onnx-community/Kokoro-82M-v1.0-ONNX";
const tts = await KokoroTTS.from_pretrained(model_id, {
dtype: "q8",
device: "wasm",
});
// Generate audio from text
const text = "Life is like a box of chocolates. You never know what you're gonna get.";
const audio = await tts.generate(text, {
voice: "af_heart", // Use tts.list_voices() to see all available voices
});
// Save audio to file
audio.save("audio.wav");
// List all available voices
const voices = tts.list_voices();
console.log("Available voices:", voices);
// Output: Array of voice IDs like ["af_heart", "af_bella", "am_michael", "bf_emma", "bm_george", ...]
```
--------------------------------
### Stream Speech Generation with Kokoro TTS (JavaScript)
Source: https://www.npmjs.com/package/kokoro-js/index
Shows how to stream audio output from the KokoroTTS model using a TextSplitterStream. This allows for real-time audio generation as text is processed, suitable for dynamic content.
```javascript
import { KokoroTTS, TextSplitterStream } from "kokoro-js";
const model_id = "onnx-community/Kokoro-82M-v1.0-ONNX";
const tts = await KokoroTTS.from_pretrained(model_id, {
dtype: "fp32", // Options: "fp32", "fp16", "q8", "q4", "q4f16"
// device: "webgpu", // Options: "wasm", "webgpu" (web) or "cpu" (node).
});
// First, set up the stream
const splitter = new TextSplitterStream();
const stream = tts.stream(splitter);
(async () => {
let i = 0;
for await (const { text, phonemes, audio } of stream) {
console.log({ text, phonemes });
audio.save(`audio-${i++}.wav`);
}
})();
// Next, add text to the stream. Note that the text can be added at different times.
// For this example, let's pretend we're consuming text from an LLM, one word at a time.
const text = "Kokoro is an open-weight TTS model with 82 million parameters. Despite its lightweight architecture, it delivers comparable quality to larger models while being significantly faster and more cost-efficient. With Apache-licensed weights, Kokoro can be deployed anywhere from production environments to personal projects. It can even run 100% locally in your browser, powered by Transformers.js!";
const tokens = text.match(/\s*\S+/g);
for (const token of tokens) {
splitter.push(token);
await new Promise((resolve) => setTimeout(resolve, 10));
}
// Finally, close the stream to signal that no more text will be added.
splitter.close();
// Alternatively, if you'd like to keep the stream open, but flush any remaining text, you can use the `flush` method.
// splitter.flush();
```
--------------------------------
### Stream Speech Generation with KokoroTTS
Source: https://www.npmjs.com/package/kokoro-js/index_activetab=readme
Streams speech generation using KokoroTTS and TextSplitterStream. This allows for processing text in chunks and receiving audio as it's generated, suitable for real-time applications. It supports various data types and devices.
```javascript
import { KokoroTTS, TextSplitterStream } from "kokoro-js";
const model_id = "onnx-community/Kokoro-82M-v1.0-ONNX";
const tts = await KokoroTTS.from_pretrained(model_id, {
dtype: "fp32", // Options: "fp32", "fp16", "q8", "q4", "q4f16"
// device: "webgpu", // Options: "wasm", "webgpu" (web) or "cpu" (node).
});
// First, set up the stream
const splitter = new TextSplitterStream();
const stream = tts.stream(splitter);
(async () => {
let i = 0;
for await (const { text, phonemes, audio } of stream) {
console.log({ text, phonemes });
audio.save(`audio-${i++}.wav`);
}
})();
// Next, add text to the stream. Note that the text can be added at different times.
// For this example, let's pretend we're consuming text from an LLM, one word at a time.
const text = "Kokoro is an open-weight TTS model with 82 million parameters. Despite its lightweight architecture, it delivers comparable quality to larger models while being significantly faster and more cost-efficient. With Apache-licensed weights, Kokoro can be deployed anywhere from production environments to personal projects. It can even run 100% locally in your browser, powered by Transformers.js!";
const tokens = text.match(/\s*\S+/g);
for (const token of tokens) {
splitter.push(token);
await new Promise((resolve) => setTimeout(resolve, 10));
}
// Finally, close the stream to signal that no more text will be added.
splitter.close();
// Alternatively, if you'd like to keep the stream open, but flush any remaining text, you can use the `flush` method.
// splitter.flush();
```
--------------------------------
### Generate Speech with KokoroTTS
Source: https://www.npmjs.com/package/kokoro-js/index_activetab=readme
Generates speech from text using the KokoroTTS class. It requires specifying a model ID and allows configuration of data type and device. The generated audio can be saved to a file.
```javascript
import { KokoroTTS } from "kokoro-js";
const model_id = "onnx-community/Kokoro-82M-v1.0-ONNX";
const tts = await KokoroTTS.from_pretrained(model_id, {
dtype: "q8", // Options: "fp32", "fp16", "q8", "q4", "q4f16"
device: "wasm", // Options: "wasm", "webgpu" (web) or "cpu" (node). If using "webgpu", we recommend using dtype="fp32".
});
const text = "Life is like a box of chocolates. You never know what you're gonna get.";
const audio = await tts.generate(text, {
// Use `tts.list_voices()` to list all available voices
voice: "af_heart",
});
audio.save("audio.wav");
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.