시작하기
-
패키지 설치
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 -
네이티브 프로젝트와 동기화
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync
플러그인을 가져와서 텍스트에서 음성을 합성하세요:
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 참조
Section titled “API 참조”speak(options)
Section titled “speak(options)”지정된 음성 설정을 사용하여 주어진 텍스트를 말합니다.
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()”진행 중인 음성 합성을 중지합니다.
await SpeechSynthesis.stop();getVoices()
Section titled “getVoices()”음성 합성에 사용 가능한 음성 목록을 가져옵니다.
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()”지원되는 언어 코드 목록을 가져옵니다.
const { languages } = await SpeechSynthesis.getSupportedLanguages();console.log('Supported languages:', languages);isSpeaking()
Section titled “isSpeaking()”음성 합성이 현재 활성 상태인지 확인합니다.
const { speaking } = await SpeechSynthesis.isSpeaking();console.log('Currently speaking:', speaking);완전한 예제
Section titled “완전한 예제”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 stop() { await SpeechSynthesis.stop(); }
async checkIfSpeaking(): Promise<boolean> { const { speaking } = await SpeechSynthesis.isSpeaking(); return speaking; }}고급 사용법
Section titled “고급 사용법”다국어 지원
Section titled “다국어 지원”// 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' });};// 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 }); }};- 음성 선택: 특정 음성 ID를 사용하기 전에 항상 사용 가능한 음성을 확인하세요
- 언어 코드: 표준 언어 코드 사용 (예: ‘en-US’, ‘es-ES’, ‘fr-FR’)
- 속도 제어: 자연스러운 음성을 위해 속도를 0.5에서 2.0 사이로 유지하세요
- 말하기 전 중지: 겹침을 피하기 위해 새 음성을 시작하기 전에 stop()을 호출하세요
- 오류 처리: 강력한 오류 처리를 위해 모든 호출을 try-catch 블록으로 감싸세요