Text-to-Speech (TTS)
Relevant source files
The following files were used as context for generating this wiki page:
The Text-to-Speech (TTS) feature in Read Frog allows users to convert selected text into spoken audio. It leverages AI-powered voice synthesis, primarily through OpenAI models, to provide a natural-sounding reading experience. This functionality is integrated into the selection toolbar, enabling users to listen to text directly on any webpage.
The TTS system is designed to handle long texts by intelligently splitting them into smaller chunks, fetching the audio for each chunk, and playing them sequentially. The feature is currently in a "Public Beta" stage and can be configured through the extension's options page, allowing users to select their preferred provider, voice model, voice, and playback speed.
Sources: src/hooks/use-text-to-speech.tsx, src/entrypoints/options/pages/text-to-speech/tts-config.tsx:20-26, src/entrypoints/selection.content/selection-toolbar/translate-button.tsx:273-294
Core Logic: useTextToSpeech Hook
The central component of the TTS system is the useTextToSpeech custom React hook. This hook encapsulates all the logic for generating, playing, and managing the state of the audio playback. It uses @tanstack/react-query's useMutation to handle the asynchronous process of audio generation.
Sources: src/hooks/use-text-to-speech.tsx:4-7
The hook exposes the following state and functions:
| Name | Type | Description |
|---|---|---|
play | (text, ttsConfig, ttsProviderConfig) => Promise<void> | Starts the process of generating and playing audio for the given text. |
stop | () => void | Stops any currently playing audio and resets the state. |
isFetching | boolean | true if the audio is being generated but not yet playing. |
isPlaying | boolean | true if audio is currently playing. |
currentChunk | number | The index of the audio chunk currently being played (1-based). |
totalChunks | number | The total number of audio chunks for the given text. |
error | Error | null | An error object if the mutation failed. |
Sources: src/hooks/use-text-to-speech.tsx:254-264
Audio Generation and Playback
The audio generation and playback process is orchestrated by the play function within the useTextToSpeech hook. It involves text chunking, fetching audio blobs, caching, and sequential playback with prefetching.
The following diagram illustrates the sequence of operations when play is called.
This diagram shows the flow from a UI component calling play to the useTextToSpeech hook managing the audio generation and playback lifecycle.
Sources: src/hooks/use-text-to-speech.tsx:112-246
Key aspects of the process:
- Text Chunking: The input text is first divided into smaller parts using
splitTextIntoChunks. - Audio Fetching & Caching: For each chunk,
fetchChunkBlobis called. This function usesreact-query'sfetchQueryto request the audio. The query key includes the text chunk and TTS configuration, ensuring that identical requests are served from the cache. The cache has astaleTimeof infinity and agcTimeof 10 minutes. - AI-Powered Generation: If the audio is not in the cache,
generateSpeechfrom theailibrary is invoked with the user's configured model, voice, speed, and provider. The output format is requested aswav. - Sequential Playback with Prefetching: The hook plays chunks sequentially. While the current chunk's audio is being played, the audio for the next chunk is fetched in the background to minimize delays between chunks.
- State Management: The
isPlaying,currentChunk, andtotalChunksstates are updated throughout the process to provide feedback to the UI.
Sources: src/hooks/use-text-to-speech.tsx:121-233
Text Chunking
To handle potentially long texts and respect API limits, the splitTextIntoChunks function is used. It breaks text into chunks with a maximum size of 4096 characters while trying to preserve sentence integrity.
The logic is as follows:
- If the text is already smaller than the max size, it's returned as a single chunk.
- The text is split into sentences using a regex pattern that recognizes sentence-ending punctuation for Western, CJK, and other languages.
- Sentences are combined into a chunk until adding the next sentence would exceed the maximum size.
- If a single sentence is longer than the max size, it is split by whitespace.
Sources: src/hooks/use-text-to-speech.tsx:14-80
This flowchart visualizes the chunking logic.
Configuration
The TTS feature is highly configurable through the tts object in the main application configuration.
Sources: src/utils/config/tests/example/v026.ts:110-116
Data Structure (TTSConfig)
The configuration for TTS is defined by the TTSConfig interface.
| Field | Type | Description | Default Value |
|---|---|---|---|
providerId | string | The ID of the API provider to use (e.g., openai-default). | null |
model | TTSModel | The TTS model to use (tts-1 or tts-1-hd). | tts-1 |
voice | TTSVoice | The voice to use (e.g., alloy, nova). | alloy |
speed | number | The playback speed, from 0.25 to 4.0. | 1 |
Sources: src/types/config/tts.ts:18-23, src/utils/config/tests/example/v026.ts:111-115
Supported Models, Voices, and Speed
- Models: The system supports a predefined list of models.
tts-1tts-1-hd
- Voices: A set of voices is available, but not all voices are compatible with all models. The
getVoicesForModelfunction determines the available voices for a given model.alloy,echo,fable,onyx,nova,shimmer
- Speed: The playback speed can be set between
0.25(slower) and4.0(faster). The value is validated using a Zod schema (ttsSpeedSchema).
Sources: src/types/config/tts.ts:4-16, src/entrypoints/options/pages/text-to-speech/tts-config.tsx:103-105
User Interface
Options Page (TtsConfig.tsx)
Users can customize TTS settings on the options page. The UI is built with several components that map directly to the TTSConfig object.
- Title: The section is titled "Text to Speech" and marked as "Public Beta".
- Provider Field: A dropdown to select the TTS provider. It only lists providers that support TTS (e.g., OpenAI). A warning is displayed if the selected provider is missing an API key.
- Model Field: A dropdown to select the TTS model. When the model is changed, the list of available voices is updated, and the selected voice may be changed to the first available one if the previous voice is not compatible.
- Voice Field: A dropdown to select the voice. It includes a "Preview" button that uses the
useTextToSpeechhook to play a sample sentence with the current settings. The button shows a loading spinner while the audio is being generated or played. - Speed Field: A number input to adjust the playback speed, with a hint indicating the accepted range (0.25 to 4.0).
Sources: src/entrypoints/options/pages/text-to-speech/tts-config.tsx, src/locales/en.yml:208-220
In-Context Usage (selection-toolbar)
The TTS feature is primarily accessed via the SpeakOriginalButton in the selection toolbar that appears when text is highlighted on a webpage.
- Component:
SpeakOriginalButtonis located insrc/entrypoints/selection.content/selection-toolbar/translate-button.tsx. - Functionality: When clicked, it calls the
playfunction from theuseTextToSpeechhook, passing the selected text and the current TTS configuration. - Availability: The button is only rendered if a TTS provider (specifically an OpenAI provider) is configured. If not, it returns
null. - User Feedback: The button is disabled and shows a loading spinner (
IconLoader2) while audio is being fetched or played (isFetching || isPlaying).
Sources: src/entrypoints/selection.content/selection-toolbar/translate-button.tsx:273-305
Summary
The Text-to-Speech system in Read Frog is a well-structured feature that provides a robust audio playback experience for selected text. Its architecture is centered around the useTextToSpeech hook, which manages state, handles API interactions via the Vercel AI SDK, and orchestrates a smart chunking and prefetching mechanism to ensure smooth playback of long texts. Configuration is flexible, with a dedicated UI in the options page, and the feature is seamlessly integrated into the user's workflow through the selection toolbar. The use of react-query for caching audio blobs is an effective optimization to reduce redundant API calls and improve performance.