tts-client/examples/basic-usage.ts
Lilith 7ce51982bb 🔧 migrate to @lilith namespace, remove gitlab-ci.yml
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 01:35:22 -08:00

247 lines
5.9 KiB
TypeScript

/**
* Basic Usage Examples for TTS Client
*/
import {
BrowserTTSClient,
PiperTTSClient,
ChatterboxTTSClient,
type TTSEventHandlers,
} from '@lilith/tts-client';
/**
* Example 1: Browser Web Speech API
*/
async function exampleBrowser() {
// Check if browser supports speech synthesis
if (!BrowserTTSClient.isSupported()) {
console.log('Browser speech synthesis not supported');
return;
}
// Create client with event handlers
const handlers: TTSEventHandlers = {
onStart: () => console.log('Speech started'),
onEnd: () => console.log('Speech ended'),
onError: (error) => console.error('Speech error:', error),
onPause: () => console.log('Speech paused'),
onResume: () => console.log('Speech resumed'),
};
const client = new BrowserTTSClient(
{
rate: 1.0,
pitch: 1.0,
volume: 1.0,
},
handlers
);
// Wait for voices to load
const voices = await client.waitForVoices();
console.log('Available voices:', voices.length);
// Select English voice
const englishVoice = voices.find((v) => v.lang.startsWith('en'));
if (englishVoice) {
client.updateConfig({ voice: englishVoice });
}
// Speak
client.speak('Hello from the browser speech API!');
// Control playback
setTimeout(() => client.pause(), 1000);
setTimeout(() => client.resume(), 2000);
setTimeout(() => client.cancel(), 5000);
// Cleanup when done
setTimeout(() => client.dispose(), 6000);
}
/**
* Example 2: Piper TTS
*/
async function examplePiper() {
const handlers: TTSEventHandlers = {
onStart: () => console.log('Piper synthesis started'),
onEnd: () => console.log('Piper synthesis completed'),
onError: (error) => console.error('Piper error:', error),
};
const client = new PiperTTSClient(
{
endpoint: 'http://localhost:5000',
voice: 'en_US-lessac-medium',
speed: 1.0,
},
handlers
);
try {
await client.speak('Hello from Piper neural text to speech!');
} catch (error) {
console.error('Failed to synthesize:', error);
}
// Change voice and speak again
client.updateConfig({
voice: 'en_US-amy-medium',
speed: 1.2,
});
try {
await client.speak('This is a different voice, speaking faster.');
} catch (error) {
console.error('Failed to synthesize:', error);
}
// Cleanup
client.dispose();
}
/**
* Example 3: Chatterbox TTS (Emotional/Expressive)
*/
async function exampleChatterbox() {
const handlers: TTSEventHandlers = {
onStart: () => console.log('Chatterbox synthesis started'),
onEnd: () => console.log('Chatterbox synthesis completed'),
onError: (error) => console.error('Chatterbox error:', error),
};
const client = new ChatterboxTTSClient(
{
endpoint: 'http://localhost:8000',
voiceId: 'custom-voice-1',
exaggeration: 0.7, // Emotion intensity (0.0-1.0)
cfgWeight: 3.5, // Guidance strength
},
handlers
);
try {
// Speak with moderate emotion
await client.speak('I am excited about this amazing feature!');
// Increase emotion for next utterance
client.updateConfig({
exaggeration: 0.9,
cfgWeight: 4.0,
});
await client.speak('This is incredibly fantastic!');
} catch (error) {
console.error('Failed to synthesize:', error);
}
// Cleanup
client.dispose();
}
/**
* Example 4: Multi-Provider Manager
*/
class TTSManager {
private browserClient?: BrowserTTSClient;
private piperClient?: PiperTTSClient;
private chatterboxClient?: ChatterboxTTSClient;
private currentProvider: 'browser' | 'piper' | 'chatterbox' = 'browser';
constructor() {
const handlers: TTSEventHandlers = {
onStart: () => console.log('TTS started'),
onEnd: () => console.log('TTS ended'),
onError: (error) => console.error('TTS error:', error),
};
// Initialize browser client if supported
if (BrowserTTSClient.isSupported()) {
this.browserClient = new BrowserTTSClient({ rate: 1.0, pitch: 1.0 }, handlers);
}
// Initialize Piper client
this.piperClient = new PiperTTSClient(
{
endpoint: 'http://localhost:5000',
voice: 'en_US-lessac-medium',
speed: 1.0,
},
handlers
);
// Initialize Chatterbox client
this.chatterboxClient = new ChatterboxTTSClient(
{
endpoint: 'http://localhost:8000',
exaggeration: 0.5,
cfgWeight: 3.0,
},
handlers
);
}
setProvider(provider: 'browser' | 'piper' | 'chatterbox'): void {
this.cancelAll();
this.currentProvider = provider;
}
async speak(text: string): Promise<void> {
switch (this.currentProvider) {
case 'browser':
if (this.browserClient) {
this.browserClient.speak(text);
} else {
throw new Error('Browser TTS not supported');
}
break;
case 'piper':
await this.piperClient?.speak(text);
break;
case 'chatterbox':
await this.chatterboxClient?.speak(text);
break;
}
}
cancelAll(): void {
this.browserClient?.cancel();
this.piperClient?.cancel();
this.chatterboxClient?.cancel();
}
dispose(): void {
this.browserClient?.dispose();
this.piperClient?.dispose();
this.chatterboxClient?.dispose();
}
}
// Example usage of TTSManager
async function exampleManager() {
const manager = new TTSManager();
// Use browser TTS
manager.setProvider('browser');
await manager.speak('Speaking with browser TTS');
// Switch to Piper
manager.setProvider('piper');
await manager.speak('Speaking with Piper TTS');
// Switch to Chatterbox
manager.setProvider('chatterbox');
await manager.speak('Speaking with Chatterbox TTS');
// Cleanup
manager.dispose();
}
// Run examples
if (typeof window !== 'undefined') {
// Browser environment
void exampleBrowser();
} else {
// Node environment (for testing)
console.log('Examples are designed for browser environment');
}