gtts is a lightweight Python library that brings Google Translate text-to-speech capabilities directly to developers and creators. It enables programmatic conversion of written text into natural sounding speech without requiring a browser or API key.
The library supports multiple languages, adjustable speech rates, and configurable output formats, making it suitable for tutorials, voiceovers, accessibility tools, and conversational applications. Understanding its architecture, configuration options, and practical usage patterns helps you integrate it smoothly into your projects.
| Parameter | Description | Default | Example Value |
|---|---|---|---|
| text | String of input text to synthesize | Required | "Hello world" |
| lang | Target language code (ISO-639) | "en" | "en", "es", "fr" |
| slow | Reduce speech rate for clarity | False | True |
| lang_check | Enable strict language validation | True | False |
| pre_processor_funcs | List of text normalization functions | [] | [custom_normalizer] |
| tokenizer_func | Custom sentence tokenizer | nltk_tokenize | my_tokenizer |
Getting Started with gtts Installation
Installing gtts is straightforward using pip, and it works with Python 3.7+ environments. The package has minimal dependencies, so setup is fast even on constrained systems.
After installation, you can validate your environment by importing gtts and checking the version. This ensures you are ready to generate audio files without encountering compatibility issues.
Core Concepts Behind gtts Architecture
gtts communicates directly with the Google Translate TTS endpoint, constructing requests that return audio streams. It abstracts the underlying HTTP calls, so you can focus on text and configuration rather than network details.
The library handles URL encoding, language selection, and data parsing internally, exposing simple methods like save() and write_to_fp(). This design keeps the interface clean while supporting advanced use cases through optional parameters.
Text Splitting and Language Configuration
By default, gtts splits long input into sentences using an NLTK tokenizer, which helps control audio chunk size and avoid timeouts. You can disable this behavior or plug in custom tokenizers for specialized workflows.
Language configuration is central to gtts, using ISO-639 codes to select voices and pronunciation styles. Proper language settings improve intelligibility and prevent unexpected fallbacks to alternative voices.
Advanced Customization and Preprocessing
Preprocessor functions allow you to normalize text before synthesis, handling abbreviations, currency, dates, and domain-specific terms. Tailoring these functions can significantly improve naturalness for niche vocabulary.
The library also supports custom tokenizer functions when sentence boundaries need fine-grained control. Combining preprocessing and custom tokenization gives precise command over how input text is segmented and pronounced.
Saving Output and Managing Audio Files
You can save synthesized audio directly to disk using the save() method, specifying the output path and file format. The library currently supports MP3 encoding with configurable bitrate and codec options where relevant.
For dynamic applications, write_to_fp() writes audio to a file-like object, enabling streaming, caching, or further processing in memory. This flexibility supports web services, CLI tools, and automation pipelines.
Best Practices and Recommendations
- Install gtts in a virtual environment to avoid dependency conflicts.
- Validate language codes and test small snippets before batch processing large documents.
- Implement retry logic and timeouts to handle transient network issues gracefully.
- Use custom preprocessors for domain-specific terms to improve pronunciation accuracy.
- Monitor usage against Google Translate policies to prevent service disruptions in production.
FAQ
Reader questions
How do I handle non-Latin scripts and special characters with gtts?
Ensure your text is properly encoded in Unicode and matches the language code you set; gtts will pass the text as-is to Google Translate, so invalid characters may cause errors or unexpected results.
Can I generate speech for commercial projects using gtts?
Yes, you can use gtts in commercial projects, but you rely on the Google Translate TTS infrastructure, which is intended for personal use and may change its terms or availability without notice.
What should I do if the Google Translate endpoint returns an error?
Check your language code, network connectivity, and text length; if errors persist, implement retries with exponential backoff and consider hosting a local TTS solution as a fallback.
How can I change the voice speed or apply custom pronunciation?
Use the slow parameter to reduce speech rate, and leverage pre_processor_funcs to normalize text or inject phoneme-level hints, though true voice selection is not supported by the Google Translate TTS API.