### Quick Start: Universal Edge TTS Source: https://github.com/travisvn/edge-tts-universal/blob/main/README.md Initialize and synthesize speech using the UniversalEdgeTTS class. This example works across Node.js, Deno, Bun, and browsers. ```typescript import { UniversalEdgeTTS } from 'edge-tts-universal'; const tts = new UniversalEdgeTTS('Hello, world!', 'en-US-EmmaMultilingualNeural'); const result = await tts.synthesize(); // Works in Node.js, Deno, Bun, and browsers! ``` -------------------------------- ### Install edge-tts-universal Source: https://github.com/travisvn/edge-tts-universal/blob/main/README.md Install the package using npm or yarn. ```bash npm install edge-tts-universal # or yarn add edge-tts-universal ``` -------------------------------- ### Initialize IsomorphicVoicesManager Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Example demonstrating the creation of an IsomorphicVoicesManager instance. This instance can be used universally across Node.js and browser environments. ```typescript const voicesManager = await IsomorphicVoicesManager.create(); // Works in both Node.js and browsers ``` -------------------------------- ### List All Available Voices Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Example demonstrating how to import and use the listVoices function to fetch and log the total number of available voices. It also shows how to use the function with a proxy server. ```typescript import { listVoices } from 'edge-tts-universal'; const voices = await listVoices(); console.log(`Found ${voices.length} voices`); // With proxy const voices = await listVoices('http://proxy:8080'); ``` -------------------------------- ### Quick Start: Universal TTS Synthesis Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Perform simple text-to-speech synthesis using the UniversalEdgeTTS class. This example also shows how to save the generated audio to a file in a Node.js environment. ```typescript import { UniversalEdgeTTS } from 'edge-tts-universal'; // Simple universal TTS (works in Node.js, browsers, Deno, Bun) const tts = new UniversalEdgeTTS('Hello, world!', 'en-US-EmmaMultilingualNeural'); const result = await tts.synthesize(); // Save audio file (Node.js example) const fs = await import('fs/promises'); const audioBuffer = Buffer.from(await result.audio.arrayBuffer()); await fs.writeFile('output.mp3', audioBuffer); ``` -------------------------------- ### Isomorphic TTS Example Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Demonstrates the universal usage of the edge-tts-universal package, including listing voices, managing them, and synthesizing speech in an environment-agnostic manner. ```APIDOC ## Isomorphic (Universal) Usage ### Description Provides an example of using the `edge-tts-universal` package in an isomorphic way, suitable for both Node.js and browser environments. It covers voice listing, management, and speech synthesis. ### Method `async universalExample(): Promise` ### Parameters None ### Request Example ```typescript import { IsomorphicCommunicate, IsomorphicVoicesManager, listVoicesIsomorphic, } from 'edge-tts-universal'; async function universalExample() { console.log('🌐 Running universal TTS example...'); try { const voices = await listVoicesIsomorphic(); console.log(`✅ Found ${voices.length} voices`); const voicesManager = await IsomorphicVoicesManager.create(); const englishVoices = voicesManager.find({ Language: 'en' }); console.log(`✅ Found ${englishVoices.length} English voices`); const communicate = new IsomorphicCommunicate( 'Hello from the universal edge-tts API!', { voice: 'en-US-EmmaMultilingualNeural', rate: '+10%', } ); const audioChunks: Buffer[] = []; let wordCount = 0; for await (const chunk of communicate.stream()) { if (chunk.type === 'audio' && chunk.data) { audioChunks.push(chunk.data); console.log(`🔊 Audio chunk: ${chunk.data.length} bytes`); } else if (chunk.type === 'WordBoundary') { wordCount++; console.log(`📝 Word ${wordCount}: "${chunk.text}"`); } } const isNode = typeof process !== 'undefined' && process.versions?.node; if (isNode) { const fs = await import('fs/promises'); await fs.writeFile('universal-output.mp3', Buffer.concat(audioChunks)); console.log('💾 Node.js: Audio saved to file'); } else { const audioBlob = new Blob(audioChunks, { type: 'audio/mpeg' }); const audioUrl = URL.createObjectURL(audioBlob); console.log(`🌐 Browser: Audio Blob created (${audioBlob.size} bytes)`); } console.log(`✅ Universal synthesis complete!`); } catch (error) { console.error('❌ Universal TTS Error:', error); } } ``` ### Response #### Success Response - **Console Logs**: Outputs information about voice discovery, audio chunk reception, and completion status. - **File Output (Node.js)**: `universal-output.mp3` file is created with the synthesized audio. - **Blob URL (Browser)**: An object URL is generated for the audio Blob. #### Response Example ``` // Example Console Output: 🌐 Running universal TTS example... ✅ Found 150 voices ✅ Found 20 English voices 🔊 Audio chunk: 1024 bytes 📝 Word 1: "Hello" ... 💾 Node.js: Audio saved to file ✅ Universal synthesis complete! ``` ``` -------------------------------- ### Quick Synthesis with EdgeTTS Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Provides a simple example of synthesizing speech using the EdgeTTS class, saving the audio to an MP3 file, and generating VTT/SRT subtitle files. Requires fs/promises for file operations. ```typescript import { EdgeTTS, createVTT, createSRT } from 'edge-tts-universal'; import fs from 'fs/promises'; async function quickSynthesis() { // Simple one-shot synthesis const tts = new EdgeTTS( 'Welcome to the simple edge-tts API!', 'en-US-EmmaMultilingualNeural', { rate: '+15%', volume: '+10%' } ); try { const result = await tts.synthesize(); // Save audio to file const audioBuffer = Buffer.from(await result.audio.arrayBuffer()); await fs.writeFile('simple-output.mp3', audioBuffer); // Generate subtitle files const vttContent = createVTT(result.subtitle); const srtContent = createSRT(result.subtitle); await fs.writeFile('subtitles.vtt', vttContent); await fs.writeFile('subtitles.srt', srtContent); console.log( `Generated audio (${result.audio.size} bytes) and ${result.subtitle.length} word boundaries` ); } catch (error) { console.error('Synthesis failed:', error); } } ``` -------------------------------- ### Quick Start: Simple Synthesis and File Saving Source: https://github.com/travisvn/edge-tts-universal/blob/main/README.md Perform a one-shot speech synthesis and save the resulting audio to an MP3 file using the simple EdgeTTS API. Requires Node.js for file system operations. ```typescript import { EdgeTTS } from 'edge-tts-universal'; import fs from 'fs/promises'; // Simple one-shot synthesis const tts = new EdgeTTS('Hello, world!', 'en-US-EmmaMultilingualNeural'); const result = await tts.synthesize(); // Save audio file const audioBuffer = Buffer.from(await result.audio.arrayBuffer()); await fs.writeFile('output.mp3', audioBuffer); ``` -------------------------------- ### Generate SRT Subtitles with SubMaker and Communicate Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Example demonstrating how to use Communicate to stream audio and SubMaker to generate SRT subtitles from WordBoundary events, merging cues every 3 words. ```typescript const communicate = new Communicate('Hello world, this is a test.'); const subMaker = new SubMaker(); for await (const chunk of communicate.stream()) { if (chunk.type === 'WordBoundary') { subMaker.feed(chunk); } } // Merge every 3 words into one subtitle subMaker.mergeCues(3); const srt = subMaker.getSrt(); console.log(srt); // Output: // 1 // 00:00:00,000 --> 00:00:01,500 // Hello world, // // 2 // 00:00:01,500 --> 00:00:02,800 // this is a test. ``` -------------------------------- ### Initialize Document Event Listener Source: https://github.com/travisvn/edge-tts-universal/blob/main/examples/browser-example.html Sets up an event listener for when the DOM is fully loaded. It pre-fills the text area with default content if it's empty, providing an immediate example for the user. ```javascript document.addEventListener('DOMContentLoaded', function () { // Set default text const textarea = document.getElementById('text'); if (!textarea.value.trim()) { textarea.value = 'Hello! This is a test of browser-based text-to-speech synthesis. If you can hear this, the CORS restrictions have been bypassed somehow!'; } }); ``` -------------------------------- ### Handle Audio and Word Boundary Chunks Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Example of iterating through the stream from IsomorphicCommunicate, handling audio chunks by logging their byte length and processing WordBoundary events to log word text and timing. ```typescript const communicate = new IsomorphicCommunicate('Hello world'); for await (const chunk of communicate.stream()) { if (chunk.type === 'audio') { // Universal audio handling console.log(`Audio chunk: ${chunk.data?.length} bytes`); } else if (chunk.type === 'WordBoundary') { // Universal word timing console.log(`Word: ${chunk.text} at ${chunk.offset}ns`); } } ``` -------------------------------- ### Simple API Synthesis with EdgeTTS Source: https://github.com/travisvn/edge-tts-universal/blob/main/FEATURES.md Use the Simple API for quick, one-shot audio generation. Instantiate EdgeTTS with text and voice, then call synthesize to get the audio and subtitle data. ```typescript import { EdgeTTS } from 'edge-tts-universal'; const tts = new EdgeTTS('Hello world', 'en-US-EmmaMultilingualNeural'); const result = await tts.synthesize(); // Returns: { audio: Blob, subtitle: WordBoundary[] } ``` -------------------------------- ### Advanced Streaming Synthesis Source: https://github.com/travisvn/edge-tts-universal/blob/main/README.md Utilize the streaming API with the Communicate class for real-time audio processing. This example captures audio chunks and writes them to an MP3 file. ```typescript import { Communicate } from 'edge-tts-universal'; import fs from 'fs/promises'; const communicate = new Communicate('Hello, world!', { voice: 'en-US-EmmaMultilingualNeural', }); const buffers: Buffer[] = []; for await (const chunk of communicate.stream()) { if (chunk.type === 'audio' && chunk.data) { buffers.push(chunk.data); } } await fs.writeFile('output.mp3', Buffer.concat(buffers)); ``` -------------------------------- ### Detect Runtime Environment and Get Implementations Source: https://context7.com/travisvn/edge-tts-universal/llms.txt Use `detectRuntime` to identify the JavaScript runtime (Node, Deno, Bun, Browser, Web Worker) and get environment-appropriate implementations for fetch, WebSocket, and crypto. Conditional logic can be applied based on the detected runtime. ```typescript import { detectRuntime, getFetch, getWebSocket, getCrypto } from 'edge-tts-universal/runtime-detection'; const runtime = detectRuntime(); console.log(runtime); // { name: 'node', isNode: true, isDeno: false, isBun: false, // isBrowser: false, isWebWorker: false, version: '20.11.0' } // Get environment-appropriate implementations const fetchImpl = getFetch(); // globalThis.fetch or cross-fetch const WSImpl = getWebSocket(); // globalThis.WebSocket or isomorphic-ws const cryptoImpl = getCrypto(); // globalThis.crypto (Node 18.17+ / browser) // Conditional logic if (runtime.isNode) { const fs = await import('fs/promises'); // ... Node.js-specific operations } else if (runtime.isBrowser) { // ... browser-specific operations } ``` -------------------------------- ### Filter Voices by Language and Gender/Locale Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Examples of using the find method on IsomorphicVoicesManager to retrieve voices. The first example finds all English voices, while the second specifically targets female US voices. ```typescript const voicesManager = await IsomorphicVoicesManager.create(); // Find all English voices (universal) const englishVoices = voicesManager.find({ Language: 'en' }); // Find female US voices (universal) const femaleUSVoices = voicesManager.find({ Gender: 'Female', Locale: 'en-US', }); ``` -------------------------------- ### Listing and Filtering Voices with VoicesManager Source: https://github.com/travisvn/edge-tts-universal/blob/main/README.md Manage available TTS voices using the VoicesManager. This example shows how to create an instance, find all English voices, and filter for specific genders and locales. ```typescript // examples/listVoices.ts import { VoicesManager } from 'edge-tts-universal'; async function main() { const voicesManager = await VoicesManager.create(); // Find all English voices const voices = voicesManager.find({ Language: 'en' }); console.log( 'English voices:', voices.map((v) => v.ShortName) ); // Find female US voices const femaleUsVoices = voicesManager.find({ Gender: 'Female', Locale: 'en-US', }); console.log( 'Female US voices:', femaleUsVoices.map((v) => v.ShortName) ); } main().catch(console.error); ``` -------------------------------- ### Universal TTS Example with Edge TTS Universal Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Demonstrates isomorphic usage of the edge-tts-universal API for voice listing, management, and synthesis. Handles environment-specific output for Node.js (saving to file) and browsers (creating audio elements). ```typescript import { IsomorphicCommunicate, IsomorphicVoicesManager, listVoicesIsomorphic, } from 'edge-tts-universal'; async function universalExample() { console.log('🌐 Running universal TTS example...'); try { // Universal voice listing const voices = await listVoicesIsomorphic(); console.log(`✅ Found ${voices.length} voices`); // Universal voice management const voicesManager = await IsomorphicVoicesManager.create(); const englishVoices = voicesManager.find({ Language: 'en' }); console.log(`✅ Found ${englishVoices.length} English voices`); // Universal TTS synthesis const communicate = new IsomorphicCommunicate( 'Hello from the universal edge-tts API!', { voice: 'en-US-EmmaMultilingualNeural', rate: '+10%', } ); const audioChunks: Buffer[] = []; let wordCount = 0; for await (const chunk of communicate.stream()) { if (chunk.type === 'audio' && chunk.data) { audioChunks.push(chunk.data); console.log(`🔊 Audio chunk: ${chunk.data.length} bytes`); } else if (chunk.type === 'WordBoundary') { wordCount++; console.log(`📝 Word ${wordCount}: "${chunk.text}"`); } } // Environment-specific handling const isNode = typeof process !== 'undefined' && process.versions?.node; if (isNode) { // Node.js - save to file const fs = await import('fs/promises'); await fs.writeFile('universal-output.mp3', Buffer.concat(audioChunks)); console.log('💾 Node.js: Audio saved to file'); } else { // Browser - create audio element const audioBlob = new Blob(audioChunks, { type: 'audio/mpeg' }); const audioUrl = URL.createObjectURL(audioBlob); console.log(`🌐 Browser: Audio Blob created (${audioBlob.size} bytes)`); } console.log(`✅ Universal synthesis complete!`); } catch (error) { console.error('❌ Universal TTS Error:', error); } } ``` -------------------------------- ### Runtime Environment Detection Source: https://context7.com/travisvn/edge-tts-universal/llms.txt Detects the current JavaScript runtime (node, deno, bun, browser, webworker, unknown) and provides boolean flags and version information. It also offers utility functions to get environment-appropriate implementations for fetch, WebSocket, and crypto. ```APIDOC ## `detectRuntime` — Runtime Environment Detection Exported from `edge-tts-universal/runtime-detection`, this utility identifies the current JavaScript runtime (`node`, `deno`, `bun`, `browser`, `webworker`, `unknown`) and exposes boolean flags plus the runtime version string. ```typescript import { detectRuntime, getFetch, getWebSocket, getCrypto } from 'edge-tts-universal/runtime-detection'; const runtime = detectRuntime(); console.log(runtime); // { name: 'node', isNode: true, isDeno: false, isBun: false, // isBrowser: false, isWebWorker: false, version: '20.11.0' } // Get environment-appropriate implementations const fetchImpl = getFetch(); // globalThis.fetch or cross-fetch const WSImpl = getWebSocket(); // globalThis.WebSocket or isomorphic-ws const cryptoImpl = getCrypto(); // globalThis.crypto (Node 18.17+ / browser) // Conditional logic if (runtime.isNode) { const fs = await import('fs/promises'); // ... Node.js-specific operations } else if (runtime.isBrowser) { // ... browser-specific operations } ``` ``` -------------------------------- ### Get SRT Subtitles from SubMaker Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Returns the generated subtitles in the standard SRT format. ```typescript getSrt(): string; ``` -------------------------------- ### Simple One-Shot Synthesis with EdgeTTS Source: https://context7.com/travisvn/edge-tts-universal/llms.txt Use the UniversalEdgeTTS class for promise-based synthesis. It returns an audio Blob and WordBoundary timing records. Save the MP3 and generate subtitle files (VTT/SRT) using provided utilities. ```typescript import { UniversalEdgeTTS, createVTT, createSRT } from 'edge-tts-universal'; import { promises as fs } from 'fs'; const tts = new UniversalEdgeTTS( 'Hello, world! Welcome to edge-tts-universal.', 'en-US-EmmaMultilingualNeural', { rate: '+15%', volume: '+0%', pitch: '+0Hz' } ); try { const result = await tts.synthesize(); // result.audio → Blob (audio/mpeg) // result.subtitle → WordBoundary[] (offset/duration in 100-ns units) // Save MP3 (Node.js) const buf = Buffer.from(await result.audio.arrayBuffer()); await fs.writeFile('output.mp3', buf); // Generate subtitle files await fs.writeFile('output.vtt', createVTT(result.subtitle)); await fs.writeFile('output.srt', createSRT(result.subtitle)); console.log(`Audio: ${result.audio.size} bytes, Words: ${result.subtitle.length}`); // Audio: 42816 bytes, Words: 8 } catch (err) { console.error('Synthesis failed:', err); } ``` -------------------------------- ### Get Timestamp Source: https://github.com/travisvn/edge-tts-universal/blob/main/examples/browser-example.html Retrieves the current date and time in ISO format, removing milliseconds and specific separators. Useful for logging or unique identifiers. ```javascript getTimestamp() { return new Date().toISOString().replace(/[\[:-\]]|\.\d{3}/g, ''); } ``` -------------------------------- ### Real-time Streaming with Subtitle Generation Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Shows how to stream audio chunks in real-time and process word boundary events to generate subtitles using SubMaker. Requires an implementation for `streamAudioChunk`. ```typescript import { Communicate, SubMaker } from 'edge-tts-universal'; async function streamWithSubtitles(text: string) { const communicate = new Communicate(text); const subMaker = new SubMaker(); for await (const chunk of communicate.stream()) { if (chunk.type === 'audio' && chunk.data) { // Stream audio in real-time (e.g., to speakers or network) await streamAudioChunk(chunk.data); } else if (chunk.type === 'WordBoundary') { subMaker.feed(chunk); // Real-time subtitle display console.log(`Word: ${chunk.text} at ${chunk.offset! / 10000}ms`); } } // Final subtitles subMaker.mergeCues(5); return subMaker.getSrt(); } async function streamAudioChunk(data: Buffer) { // Implement your audio streaming logic here // e.g., write to audio device, send to client, etc. } ``` -------------------------------- ### Advanced Streaming Usage with Communicate Source: https://github.com/travisvn/edge-tts-universal/blob/main/README.md Utilize the advanced streaming API with the Communicate class for real-time audio processing. This example streams audio chunks and concatenates them into a single file. ```typescript // examples/streaming.ts import { Communicate } from 'edge-tts-universal'; import { promises as fs } from 'fs'; import path from 'path'; const TEXT = 'Hello, world! This is a test of the new edge-tts Node.js library.'; const VOICE = 'en-US-EmmaMultilingualNeural'; const OUTPUT_FILE = path.join(__dirname, 'test.mp3'); async function main() { const communicate = new Communicate(TEXT, { voice: VOICE }); const buffers: Buffer[] = []; for await (const chunk of communicate.stream()) { if (chunk.type === 'audio' && chunk.data) { buffers.push(chunk.data); } } const finalBuffer = Buffer.concat(buffers); await fs.writeFile(OUTPUT_FILE, finalBuffer); console.log(`Audio saved to ${OUTPUT_FILE}`); } main().catch(console.error); ``` -------------------------------- ### Configure Proxy for Communicate Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Shows how to configure proxy settings for the Communicate class, supporting both HTTP and HTTPS proxies with optional authentication. ```typescript const communicate = new Communicate('Hello world', { proxy: 'http://proxy.example.com:8080', }); // Also works with HTTPS proxies const communicate2 = new Communicate('Hello world', { proxy: 'https://user:pass@proxy.example.com:3128', }); ``` -------------------------------- ### UniversalEdgeTTS (Simple API) Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Provides a simple, promise-based interface for one-shot text-to-speech synthesis. It works across various JavaScript environments including Node.js, browsers, Deno, and Bun. ```APIDOC ## UniversalEdgeTTS (Simple API) ### Description A simple, promise-based TTS class that provides a familiar API for one-shot synthesis. ### Constructor `new UniversalEdgeTTS(text: string, voice: string, options?: TTSOptions)` - **text** (string) - The text to synthesize. - **voice** (string) - The voice to use for synthesis (e.g., 'en-US-EmmaMultilingualNeural'). - **options** (TTSOptions, optional) - Configuration options for synthesis. - **rate** (string, optional) - Speech rate (e.g., '+10%'). - **volume** (string, optional) - Speech volume (e.g., '+0%'). - **pitch** (string, optional) - Speech pitch (e.g., '+0Hz'). ### Method `synthesize(): Promise` Synthesizes the text into speech and returns the audio data along with subtitle information. ### Response #### Success Response (TTSResult) - **audio** (AudioData) - The synthesized audio data. - **subtitle** (Array) - An array of subtitle objects, each containing text, start time, and end time. ### Example ```typescript import { UniversalEdgeTTS } from 'edge-tts-universal'; const tts = new UniversalEdgeTTS('Hello, world!', 'en-US-EmmaMultilingualNeural', { rate: '+10%', volume: '+0%', pitch: '+0Hz', }); const result = await tts.synthesize(); console.log('Audio size:', result.audio.size, 'bytes'); console.log('Words:', result.subtitle.length); ``` ``` -------------------------------- ### Configure Communicate Options Source: https://context7.com/travisvn/edge-tts-universal/llms.txt Instantiate `Communicate` with optional configuration parameters such as voice, rate, volume, pitch, proxy, and connection timeout. Short or full voice names can be used. ```typescript import { Communicate } from 'edge-tts-universal'; // All fields are optional const communicate = new Communicate('Full options example', { voice: 'en-US-EmmaMultilingualNeural', // default: 'en-US-EmmaMultilingualNeural' rate: '+20%', // speaking speed: "+20%", "-10%", "+0%" (default) volume: '+0%', // loudness: "+50%", "-25%", "+0%" (default) pitch: '+0Hz', // voice pitch: "+5Hz", "-10Hz", "+0Hz" (default) proxy: 'http://user:pass@proxy.corp.local:3128', // Node.js only; HTTPS proxies supported connectionTimeout: 15000, // WebSocket open timeout (ms) }); // Short voice name (preferred) new Communicate('Hi', { voice: 'en-US-GuyNeural' }); // Full voice name (also accepted) new Communicate('Hi', { voice: 'Microsoft Server Speech Text to Speech Voice (en-US, GuyNeural)' }); ``` -------------------------------- ### Import EdgeTTS via unpkg CDN Source: https://github.com/travisvn/edge-tts-universal/blob/main/examples/cdn-example.html Use this script to import the EdgeTTS class from the unpkg CDN. Ensure your environment handles CORS restrictions. ```html ``` -------------------------------- ### Streaming with Subtitles using WordBoundary Events Source: https://github.com/travisvn/edge-tts-universal/blob/main/README.md Demonstrates how to generate subtitles in real-time during audio streaming. The `stream()` method emits `WordBoundary` events that can be fed into a `SubMaker` to create subtitle files. ```typescript // examples/streaming.ts import { Communicate, SubMaker } from 'edge-tts-universal'; const TEXT = 'This is a test of the streaming functionality, with subtitles.'; const VOICE = 'en-GB-SoniaNeural'; async function main() { const communicate = new Communicate(TEXT, { voice: VOICE }); const subMaker = new SubMaker(); for await (const chunk of communicate.stream()) { if (chunk.type === 'audio' && chunk.data) { // Do something with the audio data, e.g., stream it to a client. console.log(`Received audio chunk of size: ${chunk.data.length}`); } else if (chunk.type === 'WordBoundary') { subMaker.feed(chunk); } } // Get the subtitles in SRT format. const srt = subMaker.getSrt(); console.log(' Generated Subtitles (SRT): ', srt); } main().catch(console.error); ``` -------------------------------- ### Import EdgeTTS via jsdelivr CDN Source: https://github.com/travisvn/edge-tts-universal/blob/main/examples/cdn-example.html Use this script to import the EdgeTTS class from the jsdelivr CDN. This is an alternative to unpkg for loading the library. ```html ``` -------------------------------- ### Simple API: One-Shot Synthesis and Subtitle Generation Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Utilize the Simple API for straightforward text-to-speech synthesis and generate VTT and SRT subtitle files from the synthesis result. Allows for customization of rate, volume, and pitch. ```typescript import { UniversalEdgeTTS, createVTT, createSRT } from 'edge-tts-universal'; // Universal one-shot synthesis (works everywhere) const tts = new UniversalEdgeTTS('Hello, world!', 'en-US-EmmaMultilingualNeural', { rate: '+10%', volume: '+0%', pitch: '+0Hz', }); const result = await tts.synthesize(); console.log('Audio size:', result.audio.size, 'bytes'); console.log('Words:', result.subtitle.length); // Generate subtitle files const vttSubtitles = createVTT(result.subtitle); const srtSubtitles = createSRT(result.subtitle); ``` -------------------------------- ### Isomorphic API Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Offers a universal interface that automatically detects the runtime environment (Node.js, browsers, Deno, Bun) and uses appropriate implementations for cross-platform compatibility. ```APIDOC ## Isomorphic API ### Description Provides a universal interface that automatically detects the environment and uses appropriate implementations, ensuring cross-platform compatibility. ### IsomorphicCommunicate #### Constructor `new IsomorphicCommunicate(text: string, options: CommunicateOptions)` - **text** (string) - The text to synthesize. - **options** (CommunicateOptions) - Configuration options for communication. - **voice** (string) - The voice to use for synthesis (e.g., 'en-US-EmmaMultilingualNeural'). - **rate** (string, optional) - Speech rate (e.g., '+10%'). #### Method `stream(): AsyncIterable` Returns an async iterable for streaming audio and word boundary events. ### IsomorphicVoicesManager #### Static Method `create(): Promise` Creates an instance of the VoicesManager, handling environment-specific voice fetching. #### Method `find(filter: VoiceFilter): Array` Filters available voices based on the provided criteria. ### listVoicesIsomorphic() #### Function `listVoicesIsomorphic(): Promise>` Retrieves a list of available voices in an isomorphic manner. ### Example ```typescript import { IsomorphicCommunicate, IsomorphicVoicesManager, listVoicesIsomorphic, } from 'edge-tts-universal'; // Universal communicate const communicate = new IsomorphicCommunicate('Hello, universal world!', { voice: 'en-US-EmmaMultilingualNeural', rate: '+10%', }); for await (const chunk of communicate.stream()) { if (chunk.type === 'audio') { console.log(`Audio chunk: ${chunk.data?.length} bytes`); } } // Universal voice management const voicesManager = await IsomorphicVoicesManager.create(); const englishVoices = voicesManager.find({ Language: 'en' }); console.log('English voices:', englishVoices); ``` ``` -------------------------------- ### Customize Voice Parameters Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Illustrates how to customize voice parameters such as voice, rate, volume, and pitch when initializing the Communicate class. ```typescript const communicate = new Communicate('Hello world', { voice: 'en-US-EmmaMultilingualNeural', rate: '+25%', // 25% faster volume: '+10%', // 10% louder pitch: '+2Hz', // 2Hz higher }); ``` -------------------------------- ### Create IsomorphicVoicesManager Instance Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Creates a new IsomorphicVoicesManager instance using cross-platform fetch. Optionally accepts custom voices or a proxy URL. This method is suitable for both Node.js and browser environments. ```typescript static async create(customVoices?: Voice[], proxy?: string): Promise; ``` -------------------------------- ### Instantiate Communicate and Stream Audio/Word Boundaries Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md This method streams audio data and word boundary events asynchronously. It can only be called once per Communicate instance. Handle audio chunks and word timing information as they become available. ```typescript const communicate = new Communicate('Hello world'); for await (const chunk of communicate.stream()) { if (chunk.type === 'audio') { // Handle audio data console.log(`Audio chunk: ${chunk.data?.length} bytes`); } else if (chunk.type === 'WordBoundary') { // Handle word timing information console.log(`Word: ${chunk.text} at ${chunk.offset}ms`); } } ``` -------------------------------- ### UniversalCommunicate (Advanced Streaming API) Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Enables advanced streaming capabilities for real-time audio chunk processing and fine-grained control over synthesis. Ideal for large texts and memory-efficient applications. ```APIDOC ## UniversalCommunicate (Advanced Streaming API) ### Description Provides streaming capabilities with real-time chunk processing for text-to-speech synthesis. ### Constructor `new UniversalCommunicate(text: string, options: CommunicateOptions)` - **text** (string) - The text to synthesize. - **options** (CommunicateOptions) - Configuration options for communication. - **voice** (string) - The voice to use for synthesis (e.g., 'en-US-EmmaMultilingualNeural'). - **rate** (string, optional) - Speech rate (e.g., '+10%'). - **volume** (string, optional) - Speech volume (e.g., '+0%'). - **pitch** (string, optional) - Speech pitch (e.g., '+0Hz'). ### Method `stream(): AsyncIterable` Returns an async iterable that yields chunks of audio data and word boundary events. ### Response (StreamChunk Types) - **audio**: Contains audio data chunks. - **data** (ArrayBuffer | null) - The audio data buffer. - **WordBoundary**: Contains information about word timing. - **text** (string) - The spoken word. - **offset** (number) - The start time of the word in milliseconds. ### Example ```typescript import { UniversalCommunicate } from 'edge-tts-universal'; const communicate = new UniversalCommunicate('Hello, world!', { voice: 'en-US-EmmaMultilingualNeural', rate: '+10%', }); for await (const chunk of communicate.stream()) { if (chunk.type === 'audio') { console.log(`Audio chunk: ${chunk.data?.length} bytes`); } else if (chunk.type === 'WordBoundary') { console.log(`Word: "${chunk.text}" at ${chunk.offset}ms`); } } ``` ``` -------------------------------- ### Instantiate SubMaker Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Creates a new instance of the SubMaker utility class for generating SRT subtitles. ```typescript new SubMaker(); ``` -------------------------------- ### Simple API Source: https://github.com/travisvn/edge-tts-universal/blob/main/README.md Provides a straightforward, promise-based Text-to-Speech (TTS) class for single synthesis requests. ```APIDOC ## EdgeTTS ### Description A simple, promise-based TTS class for one-shot synthesis. ### Usage ```javascript // Example usage (details not provided in source) const tts = new EdgeTTS(); tts.synthesize('Hello world').then(audio => { /* handle audio */ }); ``` ``` -------------------------------- ### createVTT() Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Creates subtitle file content in VTT (WebVTT) format from word boundary data. This function takes an array of WordBoundary objects and returns a string representing the VTT formatted subtitles. ```APIDOC ## createVTT() ### Description Creates subtitle file content in VTT (WebVTT) format from word boundary data. ### Parameters #### Parameters - `wordBoundaries` (WordBoundary[]): Array of word boundary data from Simple API ### Returns `string` - VTT formatted subtitles ### Example ```typescript import { EdgeTTS, createVTT } from 'edge-tts-universal'; const tts = new EdgeTTS('Hello world'); const result = await tts.synthesize(); const vttContent = createVTT(result.subtitle); console.log(vttContent); ``` ``` -------------------------------- ### VoicesManager.create() Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Creates a new VoicesManager instance, optionally with custom voices or a proxy. ```APIDOC ## VoicesManager.create() ### Description Creates and initializes a new VoicesManager instance. This can be used to manage and query available text-to-speech voices, with options for providing custom voice lists or specifying a proxy for API requests. ### Method `static async create(customVoices?: Voice[], proxy?: string): Promise` ### Parameters #### Parameters - **customVoices** (Voice[], optional): Custom voice list instead of fetching from API - **proxy** (string, optional): Proxy URL for API requests ### Returns `Promise` ``` -------------------------------- ### Universal API (Preferred) Source: https://github.com/travisvn/edge-tts-universal/blob/main/README.md Cross-platform TTS and voice management using Web standards for maximum compatibility. ```APIDOC ## UniversalEdgeTTS ### Description Cross-platform simple TTS using Web standards. ### Usage ```javascript // Example usage (details not provided in source) const universalTts = new UniversalEdgeTTS(); universalTts.synthesize('Universal synthesis').then(audio => { /* handle audio */ }); ``` ``` ```APIDOC ## UniversalCommunicate ### Description Universal streaming TTS for all JavaScript runtimes. ### Usage ```javascript // Example usage (details not provided in source) const universalComm = new UniversalCommunicate(); universalComm.stream('Universal streaming').on('data', chunk => { /* handle audio chunk */ }); ``` ``` ```APIDOC ## UniversalVoicesManager ### Description Cross-platform voice management. ### Usage ```javascript // Example usage (details not provided in source) const universalVm = new UniversalVoicesManager(); const universalVoices = universalVm.list(); ``` ``` ```APIDOC ## listVoicesUniversal ### Description Universal voice listing with Web APIs. ### Usage ```javascript // Example usage (details not provided in source) const universalVoiceList = await listVoicesUniversal(); ``` ``` ```APIDOC ## UniversalDRM ### Description Cross-platform security using Web Crypto API. ### Usage ```javascript // Example usage (details not provided in source) const universalDrm = new UniversalDRM(); const token = await universalDrm.generateToken(); ``` ``` -------------------------------- ### EdgeTTS / UniversalEdgeTTS — Simple One-Shot Synthesis Source: https://context7.com/travisvn/edge-tts-universal/llms.txt The `UniversalEdgeTTS` class provides a promise-based API for performing a full text-to-speech synthesis round-trip. It returns an audio Blob and an array of WordBoundary timing records. ```APIDOC ## UniversalEdgeTTS - Simple One-Shot Synthesis ### Description Performs a full synthesis round-trip and returns a `Blob` of MP3 audio alongside an array of `WordBoundary` timing records. `UniversalEdgeTTS` is an alias for forward-compatible naming; both share the same implementation via `Communicate` internally. ### Class `UniversalEdgeTTS` ### Constructor Parameters - `text` (string): The text to synthesize. - `voice` (string): The voice to use for synthesis (e.g., 'en-US-EmmaMultilingualNeural'). - `options` (object): Optional configuration for rate, volume, and pitch. - `rate` (string): Speech rate adjustment (e.g., '+15%'). - `volume` (string): Volume adjustment (e.g., '+0%'). - `pitch` (string): Pitch adjustment (e.g., '+0Hz'). ### Method `synthesize()` ### Returns - `Promise<{ audio: Blob, subtitle: WordBoundary[] }> ` - `audio`: A Blob containing the MP3 audio data. - `subtitle`: An array of `WordBoundary` objects with timing information (offset/duration in 100-ns units). ### Request Example ```typescript import { UniversalEdgeTTS, createVTT, createSRT } from 'edge-tts-universal'; import { promises as fs } from 'fs'; const tts = new UniversalEdgeTTS( 'Hello, world! Welcome to edge-tts-universal.', 'en-US-EmmaMultilingualNeural', { rate: '+15%', volume: '+0%', pitch: '+0Hz' } ); try { const result = await tts.synthesize(); // result.audio → Blob (audio/mpeg) // result.subtitle → WordBoundary[] (offset/duration in 100-ns units) // Save MP3 (Node.js) const buf = Buffer.from(await result.audio.arrayBuffer()); await fs.writeFile('output.mp3', buf); // Generate subtitle files await fs.writeFile('output.vtt', createVTT(result.subtitle)); await fs.writeFile('output.srt', createSRT(result.subtitle)); console.log(`Audio: ${result.audio.size} bytes, Words: ${result.subtitle.length}`); } catch (err) { console.error('Synthesis failed:', err); } ``` ``` -------------------------------- ### Universal API for Cross-Platform Compatibility Source: https://github.com/travisvn/edge-tts-universal/blob/main/FEATURES.md Utilize the Universal API for consistent behavior across different JavaScript environments like Node.js, browsers, Deno, and Bun. This API provides a unified interface for cross-platform development. ```typescript import { UniversalCommunicate } from 'edge-tts-universal'; // Works identically in Node.js, browsers, Deno, Bun const communicate = new UniversalCommunicate('Hello world'); ``` -------------------------------- ### Communicate Constructor Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Initializes the Communicate class for streaming text-to-speech synthesis. ```APIDOC ## Communicate Constructor ### Description Initializes the Communicate class with the text to synthesize and optional configuration options for speech synthesis. ### Parameters #### Parameters - **text** (string): The text to synthesize - **options** (CommunicateOptions, optional): Configuration options ### CommunicateOptions #### Interface ```typescript interface CommunicateOptions { voice?: string; // Voice to use (default: "en-US-EmmaMultilingualNeural") rate?: string; // Speech rate (e.g., "+20%", "-10%") volume?: string; // Volume level (e.g., "+50%", "-25%") pitch?: string; // Pitch adjustment (e.g., "+5Hz", "-10Hz") proxy?: string; // Proxy URL for requests connectionTimeout?: number; // WebSocket connection timeout in ms } ``` **Voice Format:** - Short name: `"en-US-EmmaMultilingualNeural"` - Full name: `"Microsoft Server Speech Text to Speech Voice (en-US, EmmaMultilingualNeural)"` **Rate, Volume, Pitch Format:** - Must include sign: `"+0%"`, `"-10%"`, `"+5Hz"` - Rate/Volume: percentage with % suffix - Pitch: frequency with Hz suffix ``` -------------------------------- ### EdgeTTS Constructor Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Initializes the EdgeTTS class with text, an optional voice, and optional prosody options. ```APIDOC ## EdgeTTS Constructor ### Description Initializes the EdgeTTS class with the text to synthesize, an optional voice, and optional prosody options. ### Parameters #### Parameters - **text** (string): The text to synthesize - **voice** (string, optional): Voice to use (default: "Microsoft Server Speech Text to Speech Voice (zh-CN, XiaoxiaoNeural)") - **options** (ProsodyOptions, optional): Prosody options ### ProsodyOptions #### Interface ```typescript interface ProsodyOptions { rate?: string; // Speaking rate (e.g., "+10.00%", "-20.00%") volume?: string; // Speaking volume (e.g., "+15.00%", "-10.00%") pitch?: string; // Speaking pitch (e.g., "+20Hz", "-10Hz") } ``` ``` -------------------------------- ### Communicate Options Source: https://context7.com/travisvn/edge-tts-universal/llms.txt Details the optional configuration parameters for the `Communicate` class, allowing customization of voice, speech rate, volume, pitch, proxy, and connection timeout. ```APIDOC ## `CommunicateOptions` / `IsomorphicCommunicateOptions` — Full Options Reference ```typescript import { Communicate } from 'edge-tts-universal'; // All fields are optional const communicate = new Communicate('Full options example', { voice: 'en-US-EmmaMultilingualNeural', // default: 'en-US-EmmaMultilingualNeural' rate: '+20%', // speaking speed: "+20%", "-10%", "+0%" (default) volume: '+0%', // loudness: "+50%", "-25%", "+0%" (default) pitch: '+0Hz', // voice pitch: "+5Hz", "-10Hz", "+0Hz" (default) proxy: 'http://user:pass@proxy.corp.local:3128', // Node.js only; HTTPS proxies supported connectionTimeout: 15000, // WebSocket open timeout (ms) }); // Short voice name (preferred) new Communicate('Hi', { voice: 'en-US-GuyNeural' }); // Full voice name (also accepted) new Communicate('Hi', { voice: 'Microsoft Server Speech Text to Speech Voice (en-US, GuyNeural)' }); ``` ``` -------------------------------- ### CDN Import for Browser Usage Source: https://github.com/travisvn/edge-tts-universal/blob/main/README.md Import the EdgeTTS class from a CDN (unpkg or jsdelivr) for direct use in browser environments without a build step. ```html ``` -------------------------------- ### Save Streamed Audio to File with Error Handling Source: https://github.com/travisvn/edge-tts-universal/blob/main/API.md Demonstrates streaming audio chunks from Communicate, collecting them into buffers, and saving the concatenated audio to a file. Includes error handling for cases where no audio is received. ```typescript import { Communicate, NoAudioReceived } from 'edge-tts-universal'; import fs from 'fs/promises'; async function saveToFile(text: string, filename: string) { try { const communicate = new Communicate(text, { voice: 'en-US-EmmaMultilingualNeural', }); const buffers: Buffer[] = []; for await (const chunk of communicate.stream()) { if (chunk.type === 'audio' && chunk.data) { buffers.push(chunk.data); } } if (buffers.length === 0) { throw new NoAudioReceived('No audio chunks received'); } await fs.writeFile(filename, Buffer.concat(buffers)); console.log(`Saved ${buffers.length} chunks to ${filename}`); } catch (error) { console.error('Failed to generate audio:', error); throw error; } } ``` -------------------------------- ### Isomorphic API (Legacy) Source: https://github.com/travisvn/edge-tts-universal/blob/main/README.md Legacy API providing backward compatibility for TTS and voice management across Node.js and browsers. ```APIDOC ## IsomorphicCommunicate ### Description Universal TTS class that works in Node.js and browsers. ### Usage ```javascript // Example usage (details not provided in source) const isoComm = new IsomorphicCommunicate(); isoComm.stream('Isomorphic streaming').on('data', chunk => { /* handle audio chunk */ }); ``` ``` ```APIDOC ## IsomorphicVoicesManager ### Description Universal voice management with environment detection. ### Usage ```javascript // Example usage (details not provided in source) const isoVm = new IsomorphicVoicesManager(); const isoVoices = isoVm.list(); ``` ``` ```APIDOC ## listVoicesIsomorphic ### Description Universal voice listing using cross-fetch. ### Usage ```javascript // Example usage (details not provided in source) const isoVoiceList = await listVoicesIsomorphic(); ``` ``` ```APIDOC ## IsomorphicDRM ### Description Cross-platform security token generation. ### Usage ```javascript // Example usage (details not provided in source) const isoDrm = new IsomorphicDRM(); const isoToken = await isoDrm.generateToken(); ``` ```