expo-edge-speech
Version:
Text-to-speech library for Expo using Microsoft Edge TTS service
413 lines • 12.9 kB
TypeScript
/**
* Provides expo-speech compatible public API using all internal components.
* Implements complete speech synthesis workflow with parameter validation,
* error handling, and backward compatibility.
*/
import { SpeechOptions, EdgeSpeechVoice, SpeechAPIConfig } from "./types";
/**
* Speech API class providing expo-speech compatible interface
*/
declare class SpeechAPI {
private static instance;
private static globalConfig;
private static configurationLocked;
private synthesizer;
private voiceService;
private audioService;
private connectionManager;
private initialized;
private constructor();
/**
* Get singleton instance of Speech API
*/
static getInstance(): SpeechAPI;
/**
* Configure Speech API services before initialization
*
* This method allows you to customize all internal services (AudioService, VoiceService,
* NetworkService, StorageService, ConnectionManager) before any Speech API methods are called.
* Configuration must be set before the first call to speak(), getAvailableVoicesAsync(),
* or any other Speech API method.
*
* @param config - Configuration options for all Speech API services
* @throws {Error} If called after Speech API has been initialized
*
* @example
* ```typescript
* import { Speech, SpeechAPIConfig } from 'expo-edge-speech';
*
* // Configure before using any Speech API methods
* Speech.configure({
* network: {
* maxRetries: 3,
* connectionTimeout: 8000,
* enableDebugLogging: true
* },
* connection: {
* maxConnections: 5,
* poolingEnabled: true,
* circuitBreaker: {
* failureThreshold: 3,
* recoveryTimeout: 15000
* }
* },
* audio: {
* loadingTimeout: 6000,
* platformConfig: {
* ios: { playsInSilentModeIOS: true },
* android: { shouldDuckAndroid: true }
* }
* }
* });
*
* // Now use Speech API with custom configuration
* await Speech.speak('Hello, configured world!');
* ```
*/
static configure(config: SpeechAPIConfig): void;
/**
* Initialize all services if not already initialized
*/
private initializeServices;
/**
* Internal speak method that orchestrates speech synthesis.
* Assumes parameters have been validated by the public-facing API.
* @param text The text to speak.
* @param options Validated and normalized speech options.
*/
speak(text: string, options: SpeechOptions): Promise<void>;
/**
* Get list of all available voices from Microsoft Edge TTS service
*
* @returns Promise that resolves to an array of available voices with metadata
* @throws {Error} If voice service fails to fetch voice list
*
* @example
* ```typescript
* const voices = await Speech.getAvailableVoicesAsync();
* console.log(`Found ${voices.length} voices`);
*
* // Filter by language
* const englishVoices = voices.filter(v => v.language.startsWith('en-'));
*
* // Filter by gender
* const femaleVoices = voices.filter(v => v.gender === 'Female');
*
* // Use a specific voice
* const ariaVoice = voices.find(v => v.identifier === 'en-US-AriaNeural');
* if (ariaVoice) {
* await Speech.speak('Hello!', { voice: ariaVoice.identifier });
* }
* ```
*/
getAvailableVoicesAsync(): Promise<EdgeSpeechVoice[]>;
/**
* Stop current speech synthesis and clear any queued speech
*
* @returns Promise that resolves when speech is stopped
* @throws {Error} If stopping speech fails
*
* @example
* ```typescript
* // Start speaking
* Speech.speak('This is a long sentence that we might want to stop...');
*
* // Stop after 2 seconds
* setTimeout(async () => {
* await Speech.stop();
* console.log('Speech stopped');
* }, 2000);
* ```
*/
stop(): Promise<void>;
/**
* Pause current speech synthesis
*
* @returns Promise that resolves when speech is paused
* @throws {Error} If pausing speech fails
*
* @example
* ```typescript
* // Start speaking
* await Speech.speak('This is a long sentence that we can pause and resume.');
*
* // Pause after 2 seconds
* setTimeout(async () => {
* await Speech.pause();
* console.log('Speech paused');
*
* // Resume after another 2 seconds
* setTimeout(async () => {
* await Speech.resume();
* console.log('Speech resumed');
* }, 2000);
* }, 2000);
* ```
*/
pause(): Promise<void>;
/**
* Resume previously paused speech synthesis
*
* @returns Promise that resolves when speech is resumed
* @throws {Error} If resuming speech fails
*
* @example
* ```typescript
* // Pause and resume with user interaction
* let isPaused = false;
*
* await Speech.speak('Click the button to pause or resume this speech.', {
* onStart: () => console.log('Speech started - button will control pause/resume')
* });
*
* // Button click handler
* async function togglePauseResume() {
* if (isPaused) {
* await Speech.resume();
* isPaused = false;
* } else {
* await Speech.pause();
* isPaused = true;
* }
* }
* ```
*/
resume(): Promise<void>;
/**
* Check if speech synthesis is currently active
*
* @returns Promise that resolves to true if speech is currently being synthesized or played, false otherwise
* @throws {Error} If checking speech status fails
*
* @example
* ```typescript
* // Check speaking status
* const isCurrentlySpeaking = await Speech.isSpeakingAsync();
* console.log('Currently speaking:', isCurrentlySpeaking);
*
* // Wait for speech to complete
* await Speech.speak('This will take a few seconds to complete.');
*
* while (await Speech.isSpeakingAsync()) {
* console.log('Still speaking...');
* await new Promise(resolve => setTimeout(resolve, 500));
* }
* console.log('Speech completed!');
*
* // Prevent overlapping speech
* async function safeSpeech(text: string) {
* if (await Speech.isSpeakingAsync()) {
* await Speech.stop();
* }
* await Speech.speak(text);
* }
* ```
*/
isSpeakingAsync(): Promise<boolean>;
/**
* Cleanup all resources and stop services
*
* This method should be called when you're done using the Speech API to prevent
* open handles and ensure proper resource cleanup. It will stop any active speech,
* shutdown connection managers, cleanup storage services, and reset the API state.
*
* @returns Promise that resolves when cleanup is complete
*
* @example
* ```typescript
* // Cleanup when app is closing or component unmounting
* useEffect(() => {
* return () => {
* Speech.cleanup().catch(console.error);
* };
* }, []);
*
* // Manual cleanup
* await Speech.cleanup();
* console.log('All speech resources cleaned up');
* ```
*
* @note This method will log warnings for any cleanup errors but won't throw exceptions
*/
cleanup(): Promise<void>;
/**
* Reset the Speech API state for testing purposes
* @internal Only for testing - not part of public API
*/
static resetForTesting(): void;
}
/**
* Configure Speech API services before initialization
*
* This method allows you to customize all internal services (AudioService, VoiceService,
* NetworkService, StorageService, ConnectionManager) before any Speech API methods are called.
* Configuration must be set before the first call to speak(), getAvailableVoicesAsync(),
* or any other Speech API method.
*
* @param config - Configuration options for all Speech API services
* @throws {Error} If called after Speech API has been initialized
*
* @example
* ```typescript
* import { configure, SpeechAPIConfig } from 'expo-edge-speech';
*
* // Configure before using any Speech API methods
* configure({
* network: {
* maxRetries: 3,
* connectionTimeout: 8000,
* enableDebugLogging: true
* },
* connection: {
* maxConnections: 5,
* poolingEnabled: true,
* circuitBreaker: {
* failureThreshold: 3,
* recoveryTimeout: 15000
* }
* },
* audio: {
* loadingTimeout: 6000,
* platformConfig: {
* ios: { playsInSilentModeIOS: true },
* android: { shouldDuckAndroid: true }
* }
* }
* });
* ```
*/
export declare const configure: (config: SpeechAPIConfig) => void;
/**
* Speaks the given text with the specified options.
*
* Calling this when another text is being spoken adds an utterance to queue.
* This is the main entry point for text-to-speech functionality.
*
* @param text - The text to be spoken
* @param options - Configuration options for speech synthesis (optional)
*
* @example
* ```typescript
* // Basic usage with default voice
* Speech.speak('Hello, world!');
*
* // With options
* Speech.speak('Hello!', {
* voice: 'en-US-AriaNeural',
* rate: 1.2,
* onDone: () => console.log('Finished speaking')
* });
* ```
*/
export declare const speak: (text: string, options?: SpeechOptions) => void;
/**
* Get all available voices from Microsoft Edge TTS service
*
* Returns a comprehensive list of all supported voices with their metadata
* including language, gender, and capabilities.
*
* @returns A promise that resolves with an array of available voices.
*
* @example
* ```typescript
* const voices = await Speech.getAvailableVoicesAsync();
* console.log(`Found ${voices.length} voices available`);
*
* // Find English voices
* const englishVoices = voices.filter(v => v.language.startsWith('en-'));
* ```
*/
export declare const getAvailableVoicesAsync: () => Promise<EdgeSpeechVoice[]>;
/**
* Stop current speech synthesis and clear any queued utterances
*
* Interrupts any currently playing speech and removes all pending
* speech from the queue. This provides immediate speech termination.
*
* @returns A promise that resolves when speech is stopped.
*
* @example
* ```typescript
* // Stop speech immediately
* await Speech.stop();
* console.log('All speech stopped and queue cleared');
* ```
*/
export declare const stop: () => Promise<void>;
/**
* Pause current speech synthesis
*
* Temporarily stops speech playback, allowing it to be resumed later.
*
* @returns A promise that resolves when speech is paused.
*
* @example
* ```typescript
* // Pause speech
* await Speech.pause();
* console.log('Speech paused');
* ```
*/
export declare const pause: () => Promise<void>;
/**
* Resume previously paused speech synthesis
*
* Continues playback of speech that was previously paused. If no speech
* was paused, this method does nothing.
*
* @returns A promise that resolves when speech is resumed.
*
* @example
* ```typescript
* // Resume paused speech
* await Speech.resume();
* console.log('Speech resumed');
* ```
*/
export declare const resume: () => Promise<void>;
/**
* Check if the Text-to-Speech service is currently speaking
*
* Determines whether speech synthesis is currently active. Returns true
* if speech is playing or paused, false if no speech is active.
*
* @returns A promise that resolves with a boolean indicating if speech is active.
*
* @note Will return true if speaker is paused
*
* @example
* ```typescript
* const isPlaying = await Speech.isSpeakingAsync();
* if (isPlaying) {
* console.log('Speech is currently active');
* } else {
* console.log('No speech is playing');
* }
* ```
*/
export declare const isSpeakingAsync: () => Promise<boolean>;
/**
* Cleanup all resources and stop services
*
* Performs comprehensive cleanup of all speech-related resources including
* stopping active speech, shutting down connections, and clearing storage.
* This method should be called to prevent open handles and memory leaks.
*
* @returns A promise that resolves when cleanup is complete.
*
* @example
* ```typescript
* // Cleanup when app closes
* await Speech.cleanup();
* console.log('All resources cleaned up');
* ```
*/
export declare const cleanup: () => Promise<void>;
/**
* Maximum text length for speech input.
* This constant defines the character limit for text input to the speak function.
*/
export declare const maxSpeechInputLength = 1000;
export { SpeechAPI };
export default SpeechAPI;
//# sourceMappingURL=Speech.d.ts.map