Getting Started
Ce contenu n'est pas encore disponible dans votre langue.
-
Install the package
Fenêtre de terminal npm i @capgo/capacitor-speech-synthesisFenêtre de terminal pnpm add @capgo/capacitor-speech-synthesisFenêtre de terminal yarn add @capgo/capacitor-speech-synthesisFenêtre de terminal bun add @capgo/capacitor-speech-synthesis -
Sync with native projects
Fenêtre de terminal npx cap syncFenêtre de terminal pnpm cap syncFenêtre de terminal yarn cap syncFenêtre de terminal bunx cap sync
Usage
Import the plugin and synthesize speech from text:
import { SpeechSynthesis } from '@capgo/capacitor-speech-synthesis';
// Basic text-to-speechconst speak = async () => { await SpeechSynthesis.speak({ text: 'Hello, world!', language: 'en-US' });};
// Advanced usage with voice controlconst speakWithVoice = async () => { await SpeechSynthesis.speak({ text: 'This is a test of speech synthesis.', language: 'en-US', rate: 1.0, // Speech rate: 0.1 to 10.0 pitch: 1.0, // Voice pitch: 0.5 to 2.0 volume: 1.0, // Volume: 0.0 to 1.0 voice: 'com.apple.ttsbundle.Samantha-compact' });};API Reference
speak(options)
Speaks the given text using the specified voice settings.
interface SpeakOptions { text: string; // Text to speak language?: string; // Language code (e.g., 'en-US', 'es-ES') rate?: number; // Speech rate: 0.1 to 10.0 (default: 1.0) pitch?: number; // Voice pitch: 0.5 to 2.0 (default: 1.0) volume?: number; // Volume: 0.0 to 1.0 (default: 1.0) voice?: string; // Voice identifier (get from getVoices())}
await SpeechSynthesis.speak(options);stop()
Stops any ongoing speech synthesis.
await SpeechSynthesis.stop();getVoices()
Gets the list of available voices for speech synthesis.
interface Voice { voiceURI: string; // Unique voice identifier name: string; // Human-readable voice name lang: string; // Language code default: boolean; // Whether this is the default voice}
const { voices } = await SpeechSynthesis.getVoices();console.log('Available voices:', voices);getSupportedLanguages()
Gets the list of supported language codes.
const { languages } = await SpeechSynthesis.getSupportedLanguages();console.log('Supported languages:', languages);isSpeaking()
Checks if speech synthesis is currently active.
const { speaking } = await SpeechSynthesis.isSpeaking();console.log('Currently speaking:', speaking);Complete Example
import { SpeechSynthesis } from '@capgo/capacitor-speech-synthesis';
export class TextToSpeechService { private currentVoice: string | undefined;
async init() { // Get available voices const { voices } = await SpeechSynthesis.getVoices();
// Find English voice const englishVoice = voices.find(v => v.lang.startsWith('en')); this.currentVoice = englishVoice?.voiceURI;
console.log(`Using voice: ${englishVoice?.name}`); }
async speak(text: string, options?: Partial<SpeakOptions>) { try { // Stop any ongoing speech await SpeechSynthesis.stop();
// Speak the text await SpeechSynthesis.speak({ text, language: 'en-US', rate: 1.0, pitch: 1.0, volume: 1.0, voice: this.currentVoice, ...options }); } catch (error) { console.error('Speech synthesis failed:', error); throw error; } }
async speakWithRate(text: string, rate: number) { await this.speak(text, { rate }); }
async stop() { await SpeechSynthesis.stop(); }
async checkIfSpeaking(): Promise<boolean> { const { speaking } = await SpeechSynthesis.isSpeaking(); return speaking; }
async listVoicesByLanguage(languageCode: string) { const { voices } = await SpeechSynthesis.getVoices(); return voices.filter(v => v.lang.startsWith(languageCode)); }}Advanced Usage
Multi-language Support
// Speak in different languagesconst speakMultiLanguage = async () => { await SpeechSynthesis.speak({ text: 'Hello!', language: 'en-US' });
await SpeechSynthesis.speak({ text: 'Bonjour!', language: 'fr-FR' });
await SpeechSynthesis.speak({ text: 'こんにちは!', language: 'ja-JP' });};Voice Selection
// Select a specific voiceconst selectVoice = async (languageCode: string) => { const { voices } = await SpeechSynthesis.getVoices();
// Filter voices by language const languageVoices = voices.filter(v => v.lang.startsWith(languageCode) );
// Use the first available voice if (languageVoices.length > 0) { await SpeechSynthesis.speak({ text: 'Testing voice selection', language: languageCode, voice: languageVoices[0].voiceURI }); }};Reading Long Text
// Split and speak long text in chunksconst speakLongText = async (longText: string) => { const sentences = longText.match(/[^.!?]+[.!?]+/g) || [longText];
for (const sentence of sentences) { await SpeechSynthesis.speak({ text: sentence.trim(), language: 'en-US', rate: 0.9 });
// Wait a bit between sentences await new Promise(resolve => setTimeout(resolve, 500)); }};Best Practices
- Voice Selection: Always check available voices before using a specific voice ID
- Language Codes: Use standard language codes (e.g., ‘en-US’, ‘es-ES’, ‘fr-FR’)
- Rate Control: Keep rate between 0.5 and 2.0 for natural-sounding speech
- Stop Before Speak: Call stop() before starting new speech to avoid overlap
- Error Handling: Wrap all calls in try-catch blocks for robust error handling
Troubleshooting
Common Issues
No speech output: Check device volume and ensure text is not empty Voice not found: Use getVoices() to find available voices on the device Speech interrupted: Stop any ongoing speech before starting new synthesis Language not supported: Check getSupportedLanguages() for available languages