Skip to main content
CLAIM26
Cinematic voice-generation studio with microphone, audio waveform, developer code icon, single VOICE VIA API headline and the genuine full ElevenLabs wordmark on light background.
ELEVENLABS / TEXT-TO-SPEECH API

ElevenLabs Text-to-Speech API: Generate Your First AI Voice in Python & JavaScript

Get an ElevenLabs API key, keep it server-side, install the official Python or Node.js SDK, choose an authorized voice and model, and write the returned audio chunks to output.mp3.

Artificial IntelligencePublished 14 min read
Generate my First AI Voice in Python & JavaScript with ElevenLabsAffiliate disclosure: Claim26 may earn a commission from some ElevenLabs links at no extra cost to you. Pricing and product claims are checked against official sources.
GOALA first MP3 generated through a documented API request, with complete downloadable examples for both languages and a checklist covering permissions, costs and errors.Pricing and product details checked against official sources on November 2, 2026.
Cinematic voice-generation studio with microphone, audio waveform, developer code icon, single VOICE VIA API headline and the genuine full ElevenLabs wordmark on light background.
KEY TAKEAWAYCreate an MP3 from a few lines of Python or JavaScript with the official ElevenLabs SDK, then learn how to secure credentials, monitor credits and extend the workflow.

What the ElevenLabs Text-to-Speech API does differently

The ElevenLabs Text-to-Speech API turns text into a voice recording from your own code, rather than requiring a person to paste words into a web editor every time. A simple application can accept a sentence, choose a permitted voice, make a server-side API request and write the returned MP3. The use case is especially relevant for accessible website narration, product demos, content workflows and applications that need repeatable speech generation.

The provider calls its developer platform ElevenAPI. It supplies official Python and Node.js libraries. You will build a small example in both languages, save a real audio file and learn how to distinguish a voice ID, model ID and audio format. This is a beginner-friendly integration tutorial; Claim26 reviewed source code and official documentation but did not use a paid account to generate audio for this article.

Choose the API only when it fits your workflow

If you need to narrate a few paragraphs occasionally, the normal ElevenCreative website may be simpler. The API is preferable when you need to send text from your own software, repeat the same process for many approved inputs, control outputs through code or integrate voice generation into a website backend. It does not automatically give you permission to clone someone else's voice or publish generated speech commercially.

Start with a single short phrase. Keep long-form books, real-time conversational agents and multiple-speaker dialogue outside your first test. They introduce separate concerns such as splitting text, streaming, latency, usage limits and licensing. A basic synchronous conversion proves that the key, voice, model and file-writing logic are connected before you add a larger system.

Before starting: what you need

Prepare an ElevenLabs account with API access and sufficient remaining credits, a computer with current Python or Node.js, a text editor and a project folder you control. You also need a voice ID that your account is allowed to use. The examples below use the official documentation's sample voice ID, JBFqnCBsd6RMkjVDRZzb, associated with the George example. If that voice is unavailable or your permissions differ, select one from your own Voice Library.

The examples use the model ID eleven_v4 and the output format mp3_44100_128. Model availability, usage charges and format restrictions can change with account level. Consult your dashboard before running scripts; attempting the same call repeatedly can consume credits even when the first resulting file was not saved. The examples deliberately contain no API key, paid subscription promise or claimed benchmark.

Step 1 — Create an API key and keep it private

Open your ElevenLabs account and navigate to API Keys in the developer or workspace settings. Create a key with only the permissions your project needs. The official quickstart recommends storing it as an environment variable in a local .env file, rather than placing it directly in source code. Your file contains one line: ELEVENLABS_API_KEY=your_key_here (replace the placeholder privately). Keep this .env file out of Git with a .gitignore entry.

Do not paste the real key into a public GitHub repository, a webpage, a shared screenshot, browser JavaScript or a customer-facing app. The Python and Node scripts should execute on your own trusted computer or backend. If a key is accidentally exposed, revoke or rotate it promptly. Never ask a site's visitor to supply your private ElevenLabs key: their browser would then have access to credentials that belong only on your server.

Step 2 — Install Python and generate the first MP3

Open a terminal in a new project folder and run python -m pip install elevenlabs python-dotenv. In that same folder, create the .env file with your real ELEVENLABS_API_KEY entry. Then save the Claim26 sample as elevenlabs-tts-api-python.py and run python elevenlabs-tts-api-python.py. If Python is installed as python3 on your system, adapt the command. The downloadable complete script is at https://www.claim26.com/examples/elevenlabs-tts-api-python.py.

The Python script reads the secret with load_dotenv and os.getenv, constructs ElevenLabs(api_key=key), calls client.text_to_speech.convert with text, voice_id, model_id and output_format, and iterates over the returned audio chunks while writing them to output.mp3. On success it prints the saved filename. Open the MP3 in your usual audio player to listen. This is based on the official ElevenAPI quickstart, not a recording generated by Claim26.

Step 3 — Do the same from JavaScript with Node.js

Create a second project folder with a recent supported version of Node.js. Install the official SDK with npm install @elevenlabs/elevenlabs-js dotenv. Create the same private .env file in the project folder. Save the JavaScript sample as elevenlabs-tts-api-node.mjs and execute it using node elevenlabs-tts-api-node.mjs. The complete runnable source is available at https://www.claim26.com/examples/elevenlabs-tts-api-node.mjs.

The Node script imports dotenv/config, ElevenLabsClient and Node's writeFile utility. The SDK request uses the camelCase options modelId and outputFormat, unlike the Python SDK's model_id and output_format. The returned audio is consumed as a stream of chunks, concatenated into a Buffer and saved as output.mp3. This matters: do not assume a streaming response is already a fully assembled MP3 string. The code follows the official ElevenLabs TypeScript/Node quickstart pattern.

Step 4 — Understand voice_id, model_id and output_format

The voice_id selects which voice reads your text; it is not your account ID or an API credential. The model_id controls the synthesis model's characteristics and supported languages. The output_format determines the audio encoding, sample rate and bitrate. In the example, mp3_44100_128 means an MP3 at 44.1 kHz and 128 kbps. Do not replace these values by guesses: use actual voice and model identifiers available in your ElevenLabs account.

Use ElevenLabs' Voice Library to review voice permissions and choose a suitable voice for your intended language. The models list can confirm supported text-to-speech capabilities. Some higher-quality audio formats require higher subscription tiers. If a request returns an unsupported-format error, choose a format supported by the account instead of assuming the audio stream is corrupt. See the official API reference at https://elevenlabs.io/docs/api-reference/text-to-speech/convert.

Which model should a beginner choose in 2026?

Eleven v4 is a reasonable quality-focused starting point because ElevenLabs currently uses it in its introductory Text-to-Speech documentation. If latency matters more than expressive detail, investigate Eleven v4 Turbo or the Flash family and compare documented limits before building a live feature. Multilingual v2 is still documented for stable longer-form output in several languages. Model availability and supported parameters can differ by endpoint.

Do not copy voice settings indiscriminately from older tutorials. ElevenLabs notes that Eleven v4 has a different set of supported adjustments than some previous models: a parameter used by multilingual_v2 or Flash may be unsupported in v4. Begin with the model defaults and a short phrase, confirm the response, then add only settings listed for your chosen model. The latest model is not guaranteed to be the fastest or best for every language or use case.

How the underlying HTTP request works

The SDKs call the ElevenLabs API over HTTPS. The direct Text-to-Speech endpoint is POST https://api.elevenlabs.io/v1/text-to-speech/{voice_id}. It accepts a request containing your text and model_id, with a valid API key conveyed privately through the xi-api-key header, and returns audio bytes. The output_format query option selects the encoding. The SDK manages most of these details for you.

For debugging you can compare the SDK's inputs against the official HTTP reference, but avoid pasting real keys into a browser console or public curl snippet. A short test request is easier to reason about than a long audiobook chapter. Use the correct method, a voice ID that exists and an authorized model. A successful HTTP response should be written as binary audio, not interpreted as a JSON message.

Direct conversion versus the asynchronous speech-generation flow

ElevenLabs also documents POST /v1/flows/text-to-speech. Unlike the direct conversion endpoint, it starts an asynchronous job and initially returns an ID with status pending. You then use the corresponding retrieval endpoint and job lifecycle. It is intended for workflows or models supported by that asynchronous route; it is not a drop-in replacement for a request whose response is expected to be MP3 bytes immediately.

The current flow documentation lists supported request shapes by model. Do not assume the newest eleven_v4 direct-conversion example is accepted there, or that sending its parameters unchanged will work. For your first speech file, use the ordinary SDK convert call documented above. Add job polling only when your application truly requires asynchronous generation and the specific model is supported.

How much will a first API request cost?

ElevenLabs accounts use credits, and text-to-speech usage is generally based on the number of characters and model-specific charging rules. The exact conversion from characters to credits varies by model and plan, with some fast models discounted. Thus a 100-character script is not always exactly 100 credits. Run a short test and review the real usage inside your account before estimating the cost of a complete website or audiobook.

Official API documentation also describes raw-response headers that can expose a character-cost or request ID. Those are useful for monitoring, but your actual billing and plan allowances remain the source of truth. A repeated failed or successful attempt should not be presented as free simply because the output file was overwritten locally. See https://elevenlabs.io/docs/api-reference/introduction and the current pricing section in your account.

What to do when the API fails: 401, 422 and 429

A 401 generally means your API key is invalid, absent or unauthorized. Check your environment variable and the key's permissions without printing its value in logs. A 422 usually indicates an invalid payload, a model/voice mismatch or text that exceeds a limit. Read the provider's error response and compare your request to the documented schema. Repeating the same invalid request usually does not fix it.

A 429 can mean you hit a rate or concurrency limit. Back off and retry conservatively rather than firing requests in a tight loop. The SDK may already retry some temporary errors, so understand its defaults to avoid duplicate work or unnecessary charges. If the service returns a 5xx problem, use bounded retries and inspect request IDs. The vendor's API integration guide details these categories: https://elevenlabs.io/blog/text-to-speech-api-integration.

Should you use streaming for a live website?

When users need to start listening before the entire sentence is generated, streaming can reduce the perceived wait by sending audio chunks earlier. The text_to_speech.stream SDK method and streaming HTTP endpoints are documented separately from the ordinary convert flow. A live player needs buffering and error handling rather than simply saving all chunks to one file after completion.

For a blog narration tool that can pre-generate clips, a single conversion plus caching may be simpler, cheaper to operate and more reliable than generating the same paragraph on every page visit. Do not put the ElevenLabs API key into a frontend page to avoid writing a backend. Run generation on a trusted server and deliver the permitted audio file to the reader through your usual storage or delivery process.

Permissions, commercial usage and protecting users

Generate speech only from text you are entitled to use and with voices for which you have the necessary rights and provider permissions. Cloning a real person's voice may require explicit authorization and separate verification. API access does not automatically grant rights to impersonate someone or resell recordings. Review the commercial use conditions of your actual ElevenLabs plan, and avoid making voice recordings that mislead listeners about who is speaking.

Protect API credentials and avoid storing unnecessary personal text in logs. If your application takes input from visitors, validate length and content, restrict who can generate audio and limit spending per user. Treat user-submitted text as data, not as instructions for your backend. Add billing alerts, appropriate consent notices and moderation controls where relevant. A simple script is only the first step toward a production service.

Next step: turn one verified MP3 into a useful feature

Once the sample creates output.mp3 and you can listen to it, repeat the experiment with a voice you have permission to use and a second short phrase. If you need stable pronunciation, investigate ElevenLabs pronunciation dictionaries; if you need custom voices, read the voice cloning guide; and if you are deciding whether to pay for additional capabilities, compare the Starter and Creator plans against your real credit needs.

ElevenLabs can be a useful voice infrastructure partner for software teams, but its value depends on actual requirements, usage volume and rights. Claim26 may earn an affiliate commission if you subscribe through its disclosed ElevenLabs links, without additional cost to you. The tutorial and the downloadable examples are educational, based on public official documentation; Claim26 does not claim to have run the code against a live paid account.

BEFORE YOU CHOOSE

Check these four signals.

✓Keep your API key in an environment variable

✓Use a real voice ID and a supported model

✓Save streaming bytes as binary MP3

✓Check actual credit use and permissions before scaling

MOVE FROM IDEA TO TESTING

The safest way to choose is to build a small real-world workflow.

Test the part of the customer journey that matters most before moving your entire system.

Generate my First AI Voice in Python & JavaScript with ElevenLabs
PRIMARY SOURCES

Official sources for this guide

Software pricing and features can change. Review the official documentation below before choosing a product or plan.

READ NEXT

Continue with the question that is most likely to affect your next decision.

ElevenLabs text-to-speech voiceover guide with an audio studio, illustrative narration workflow, waveform preview and the ElevenLabs logo.
Artificial Intelligence · 14 min readHow to Create an ElevenLabs Voiceover: Script, Settings and Audio ExportRead the guide →
Cinematic audio-production console with four copper-lit controls, microphone, official white ElevenLabs logo and prominent Master Your Voice title.
Artificial Intelligence · 13 min readElevenLabs Voice Settings Explained: Stability, Similarity, Style and SpeedRead the guide →
Sunlit premium recording studio with a microphone, amber audio waveform, official ElevenLabs logo and a large Find Your Perfect Voice headline.
Artificial Intelligence · 12 min readElevenLabs Voice Library: How to Find the Right AI VoiceRead the guide →
EXPLORE AUDIO CREATION

Explore ElevenLabs for voice and dubbing.

Voice tools, dubbing features, usage rights and credits depend on the selected plan. Affiliate disclosure: Claim26 publishes independent guides and may earn a commission from eligible purchases through this link, at no extra cost to you.

ElevenLabs · Explore ElevenLabs