Commencer
-
Installez le 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 -
Synchronisation avec les projets natifs
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
Utilisation
Section titled “Utilisation”Importez le plugin et synthétisez la parole à partir du texte :
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 Référence
Section titled “API Référence”speak(options)
Section titled “speak(options)”Prononce le texte donné en utilisant les paramètres vocaux spécifiés.
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);arrête()
Section titled “arrête()”Arrête toute synthèse vocale en cours.
await SpeechSynthesis.stop();getVoices()
Section titled “getVoices()”Obtient la liste des voix disponibles pour la synthèse vocale.
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()
Obtient la liste des codes de langue pris en charge.
const { languages } = await SpeechSynthesis.getSupportedLanguages();console.log('Supported languages:', languages);isSpeaking()
Section titled “isSpeaking()”Vérifie si la synthèse vocale est actuellement active.
const { speaking } = await SpeechSynthesis.isSpeaking();console.log('Currently speaking:', speaking);Exemple complet
Section titled “Exemple complet”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)); }}Utilisation avancée
Section titled “Utilisation avancée”Prise en charge multilingue
Section titled “Prise en charge multilingue”// 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
Section titled “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
Section titled “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)); }};## meilleures pratiques
- Sélection vocale : vérifiez toujours les voix disponibles avant d’utiliser un identifiant vocal spécifique.
- Codes de langue : utilisez des codes de langue standard (par exemple, « en-US », « es-ES », « fr-FR »)
- Contrôle du débit : maintenez le débit entre 0,5 et 2,0 pour une parole au son naturel
- Stop Before Speak : appelez stop() avant de commencer un nouveau discours pour éviter les chevauchements
- Gestion des erreurs : enveloppez tous les appels dans des blocs try-catch pour une gestion robuste des erreurs
Dépannage
Section titled “Dépannage”Problèmes courants
Section titled “Problèmes courants”Aucune sortie vocale : vérifiez le volume de l’appareil et assurez-vous que le texte n’est pas vide Voix introuvable : utilisez getVoices() pour rechercher les voix disponibles sur l’appareil Discours interrompu : Arrêtez tout discours en cours avant de commencer une nouvelle synthèse Langue non prise en charge : vérifiez getSupportedLanguages() pour les langues disponibles