Erste Schritte
-
Paket installieren
Terminal-Fenster npm i @capgo/capacitor-speech-synthesisTerminal-Fenster pnpm add @capgo/capacitor-speech-synthesisTerminal-Fenster yarn add @capgo/capacitor-speech-synthesisTerminal-Fenster bun add @capgo/capacitor-speech-synthesis -
Mit nativen Projekten synchronisieren
Terminal-Fenster npx cap syncTerminal-Fenster pnpm cap syncTerminal-Fenster yarn cap syncTerminal-Fenster bunx cap sync
Nutzung
Section titled “Nutzung”Importieren Sie das Plugin und synthetisieren Sie Sprache aus 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 Referenz
Section titled “API Referenz”sprechen(Optionen)
Section titled “sprechen(Optionen)”Spricht den angegebenen Text mit den angegebenen Spracheinstellungen.
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()
Section titled “stop()”Stoppt jede laufende Sprachsynthese.
await SpeechSynthesis.stop();getVoices()
Section titled “getVoices()”Ruft die Liste der verfügbaren Stimmen für die Sprachsynthese ab.
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()
Section titled “getSupportedLanguages()”Ruft die Liste der unterstützten Sprachcodes ab.
const { languages } = await SpeechSynthesis.getSupportedLanguages();console.log('Supported languages:', languages);isSpeaking()
Section titled “isSpeaking()”Überprüft, ob die Sprachsynthese derzeit aktiv ist.
const { speaking } = await SpeechSynthesis.isSpeaking();console.log('Currently speaking:', speaking);Vollständiges Beispiel
Section titled “Vollständiges Beispiel”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)); }}Erweiterte Nutzung
Section titled “Erweiterte Nutzung”Mehrsprachige Unterstützung
Section titled “Mehrsprachige Unterstützung”// 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' });};Sprachauswahl
Section titled “Sprachauswahl”// 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 }); }};Langtext lesen
Section titled “Langtext lesen”// 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)); }};Bewährte Methoden
Section titled “Bewährte Methoden”- Stimmenauswahl: Überprüfen Sie immer die verfügbaren Stimmen, bevor Sie eine bestimmte Stimmen-ID verwenden
- Sprachcodes: Verwenden Sie Standard-Sprachcodes (z. B. „en-US“, „es-ES“, „fr-FR“).
- Ratensteuerung: Halten Sie die Rate zwischen 0,5 und 2,0 für eine natürlich klingende Sprache
- Vor dem Sprechen stoppen: Rufen Sie stop() auf, bevor Sie mit einer neuen Rede beginnen, um Überschneidungen zu vermeiden
- Fehlerbehandlung: Umfassen Sie alle Aufrufe in Try-Catch-Blöcken für eine robuste Fehlerbehandlung
Fehlerbehebung
Section titled “Fehlerbehebung”Häufige Probleme
Section titled “Häufige Probleme”Keine Sprachausgabe: Überprüfen Sie die Lautstärke des Geräts und stellen Sie sicher, dass der Text nicht leer ist Stimme nicht gefunden: Verwenden Sie getVoices(), um verfügbare Stimmen auf dem Gerät zu finden Sprache unterbrochen: Stoppen Sie jede laufende Sprache, bevor Sie mit der neuen Synthese beginnen Sprache nicht unterstützt: Überprüfen Sie getSupportedLanguages() auf verfügbare Sprachen