Passer au contenu

Commencer

  1. Installez le package

    Fenêtre de terminal
    npm i @capgo/capacitor-speech-synthesis
  2. Synchronisation avec les projets natifs

    Fenêtre de terminal
    npx cap sync

Importez le plugin et synthétisez la parole à partir du texte :

import { SpeechSynthesis } from '@capgo/capacitor-speech-synthesis';
// Basic text-to-speech
const speak = async () => {
await SpeechSynthesis.speak({
text: 'Hello, world!',
language: 'en-US'
});
};
// Advanced usage with voice control
const 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'
});
};

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 toute synthèse vocale en cours.

await SpeechSynthesis.stop();

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);

Vérifie si la synthèse vocale est actuellement active.

const { speaking } = await SpeechSynthesis.isSpeaking();
console.log('Currently speaking:', speaking);
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));
}
}
// Speak in different languages
const 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'
});
};
// Select a specific voice
const 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
});
}
};
// Split and speak long text in chunks
const 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

  1. Sélection vocale : vérifiez toujours les voix disponibles avant d’utiliser un identifiant vocal spécifique.
  2. Codes de langue : utilisez des codes de langue standard (par exemple, « en-US », « es-ES », « fr-FR »)
  3. Contrôle du débit : maintenez le débit entre 0,5 et 2,0 pour une parole au son naturel
  4. Stop Before Speak : appelez stop() avant de commencer un nouveau discours pour éviter les chevauchements
  5. Gestion des erreurs : enveloppez tous les appels dans des blocs try-catch pour une gestion robuste des erreurs

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