Prerequisites
Before you begin, make sure you have:- Installed the ElevenLabs Python SDK (Installation Guide)
- An ElevenLabs API key (Get one here)
Your First Text-to-Speech
Let’s generate high-quality speech audio from text in just a few lines of code.Set Up Your Environment
Create a new Python file and set up your environment variables:
Make sure you have a
.env file with your API key: ELEVENLABS_API_KEY=your_api_key_hereInitialize the Client
Create an ElevenLabs client instance:The client will automatically use the
ELEVENLABS_API_KEY from your environment variables.Generate Audio
Convert text to speech using the This generates audio using the Eleven v3 model with a pre-configured voice.
text_to_speech.convert() method:Complete Example
Here’s the complete working example:Understanding the Code
Model Selection
The SDK supports multiple AI models optimized for different use cases:Voice IDs
Thevoice_id parameter specifies which voice to use. In the example, we use "JBFqnCBsd6RMkjVDRZzb" which is a pre-made voice. You can:
- Browse available voices in the Voice Lab
- List all your voices programmatically (see below)
- Create custom voice clones
Output Formats
Supported output formats include:mp3_44100_128- MP3 at 44.1kHz, 128kbpsmp3_44100_192- MP3 at 44.1kHz, 192kbpspcm_16000- Raw PCM at 16kHzpcm_22050- Raw PCM at 22.05kHzpcm_24000- Raw PCM at 24kHzpcm_44100- Raw PCM at 44.1kHz
Exploring Available Voices
List all available voices in your account:Saving Audio to a File
Instead of playing audio, save it to a file:Streaming Audio
For real-time applications, stream audio as it’s being generated:Using Async Client
For async/await support, useAsyncElevenLabs:
Next Steps
Now that you’ve generated your first audio, explore more features:Voice Cloning
Clone voices from audio samples
Conversational AI
Build interactive AI agents
Speech-to-Text
Transcribe audio with high accuracy
API Reference
Explore the complete API documentation
Troubleshooting
Audio Not Playing
If theplay() function doesn’t work:
- Ensure PyAudio is installed:
pip install elevenlabs[pyaudio] - Check your system audio settings
- Try saving to a file first to verify the audio was generated
Authentication Errors
If you see authentication errors:- Verify your API key is correct
- Check that the
.envfile is in the correct directory - Ensure
python-dotenvis installed:pip install python-dotenv
Model Not Available
If a model isn’t available:- Check your subscription plan
- Verify the model ID is correct
- See available models for your plan