Guida introduttiva
Copy a setup prompt with the install steps and the full markdown guide for this plugin.
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-speech-synthesis`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/it/docs/plugins/speech-synthesis/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
-
Installa il pacchetto
Terminal window npm i @capgo/capacitor-speech-synthesisTerminal window pnpm add @capgo/capacitor-speech-synthesisTerminal window yarn add @capgo/capacitor-speech-synthesisTerminal window bun add @capgo/capacitor-speech-synthesis -
Sincronizza con i progetti nativi
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync
Utilizzo
Section titled “Utilizzo”Importa il plugin e sintetizza il parlato dal testo:
import { SpeechSynthesis } from '@capgo/capacitor-speech-synthesis';
// Sintesi vocale di baseconst speak = async () => { await SpeechSynthesis.speak({ text: 'Ciao, mondo!', language: 'en-US' });};
// Utilizzo avanzato con controllo della voceconst speakWithVoice = async () => { await SpeechSynthesis.speak({ text: 'Questo è un test della sintesi vocale.', language: 'en-US', rate: 1.0, // Velocità del parlato: da 0.1 a 10.0 pitch: 1.0, // Tono della voce: da 0.5 a 2.0 volume: 1.0, // Volume: da 0.0 a 1.0 voice: 'com.apple.ttsbundle.Samantha-compact' });};Riferimento API
Section titled “Riferimento API”speak(options)
Section titled “speak(options)”Parla il testo fornito utilizzando le impostazioni vocali specificate.
interface SpeakOptions { text: string; // Testo da pronunciare language?: string; // Codice lingua (es. 'en-US', 'es-ES') rate?: number; // Velocità del parlato: da 0.1 a 10.0 (predefinito: 1.0) pitch?: number; // Tono della voce: da 0.5 a 2.0 (predefinito: 1.0) volume?: number; // Volume: da 0.0 a 1.0 (predefinito: 1.0) voice?: string; // Identificatore della voce (ottieni da getVoices())}
await SpeechSynthesis.speak(options);stop()
Section titled “stop()”Interrompe qualsiasi sintesi vocale in corso.
await SpeechSynthesis.stop();getVoices()
Section titled “getVoices()”Ottiene l’elenco delle voci disponibili per la sintesi vocale.
interface Voice { voiceURI: string; // Identificatore univoco della voce name: string; // Nome della voce leggibile lang: string; // Codice lingua default: boolean; // Se questa è la voce predefinita}
const { voices } = await SpeechSynthesis.getVoices();console.log('Voci disponibili:', voices);getSupportedLanguages()
Section titled “getSupportedLanguages()”Ottiene l’elenco dei codici lingua supportati.
const { languages } = await SpeechSynthesis.getSupportedLanguages();console.log('Lingue supportate:', languages);isSpeaking()
Section titled “isSpeaking()”Verifica se la sintesi vocale è attualmente attiva.
const { speaking } = await SpeechSynthesis.isSpeaking();console.log('Attualmente in riproduzione:', speaking);Esempio completo
Section titled “Esempio completo”import { SpeechSynthesis } from '@capgo/capacitor-speech-synthesis';
export class TextToSpeechService { private currentVoice: string | undefined;
async init() { // Ottieni le voci disponibili const { voices } = await SpeechSynthesis.getVoices();
// Trova voce inglese const englishVoice = voices.find(v => v.lang.startsWith('en')); this.currentVoice = englishVoice?.voiceURI;
console.log(`Utilizzo della voce: ${englishVoice?.name}`); }
async speak(text: string, options?: Partial<SpeakOptions>) { try { // Interrompi qualsiasi parlato in corso await SpeechSynthesis.stop();
// Parla il testo await SpeechSynthesis.speak({ text, language: 'en-US', rate: 1.0, pitch: 1.0, volume: 1.0, voice: this.currentVoice, ...options }); } catch (error) { console.error('Sintesi vocale fallita:', 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)); }}Utilizzo avanzato
Section titled “Utilizzo avanzato”Supporto multilingue
Section titled “Supporto multilingue”// Parla in diverse lingueconst 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' });};Selezione della voce
Section titled “Selezione della voce”// Seleziona una voce specificaconst selectVoice = async (languageCode: string) => { const { voices } = await SpeechSynthesis.getVoices();
// Filtra le voci per lingua const languageVoices = voices.filter(v => v.lang.startsWith(languageCode) );
// Usa la prima voce disponibile if (languageVoices.length > 0) { await SpeechSynthesis.speak({ text: 'Testando la selezione della voce', language: languageCode, voice: languageVoices[0].voiceURI }); }};Lettura di testo lungo
Section titled “Lettura di testo lungo”// Dividi e parla testo lungo in frammenticonst 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 });
// Aspetta un po' tra le frasi await new Promise(resolve => setTimeout(resolve, 500)); }};Best practice
Section titled “Best practice”- Selezione della voce: Verifica sempre le voci disponibili prima di utilizzare un ID voce specifico
- Codici lingua: Utilizza codici lingua standard (es. ‘en-US’, ‘es-ES’, ‘fr-FR’)
- Controllo della velocità: Mantieni la velocità tra 0.5 e 2.0 per un parlato dal suono naturale
- Interrompi prima di parlare: Chiama stop() prima di avviare un nuovo parlato per evitare sovrapposizioni
- Gestione degli errori: Racchiudi tutte le chiamate in blocchi try-catch per una gestione robusta degli errori
Risoluzione dei problemi
Section titled “Risoluzione dei problemi”Problemi comuni
Section titled “Problemi comuni”Nessun output vocale: Verifica il volume del dispositivo e assicurati che il testo non sia vuoto Voce non trovata: Usa getVoices() per trovare le voci disponibili sul dispositivo Parlato interrotto: Interrompi qualsiasi parlato in corso prima di avviare una nuova sintesi Lingua non supportata: Verifica getSupportedLanguages() per le lingue disponibili