Blog

Build your own text-to-speech applications with Amazon Polly

Markdown

Build a basic, serverless application that uses Amazon Polly to convert text to speech.

Amazon Polly turns text into speech through an API. A speech-enabled application can use it to read articles, recipes or other text aloud. This guide starts with a small Python example that saves an MP3, then explains how to extend it into a serverless application that lets a user submit text and retrieve the audio.

This guide adapts Tomasz Stachlewski’s AWS article, published March 24, 2017, with an updated example and architecture.

Choose a voice and prepare AWS access

Choose a Region where Amazon Polly is available (AWS Services by Region). Install Python 3 and Boto3, and configure AWS credentials using a supported provider such as a named profile or an IAM role. Give that identity permission to call polly:SynthesizeSpeech; do not put access keys in source code or a browser.

Select a voice and engine supported in your Region. The voice reference describes available combinations. The example uses Joanna with the standard engine. Change both settings together if you choose a different combination. Polly usage can incur charges; consult AWS pricing before running it.

Convert a short text to an MP3

Save the following as speak.py. It sends a complete plain-text input in one request, closes the response stream and writes the returned audio in binary mode.

from contextlib import closing
from pathlib import Path

import boto3


def synthesize_to_file(text, output_path):
    if not isinstance(text, str) or not text.strip():
        raise ValueError("Provide non-empty text")
    # A conservative example limit in Unicode code points, not an SSML parser.
    if len(text) > 1000:
        raise ValueError("This example accepts at most 1000 characters")

    polly = boto3.client("polly")
    response = polly.synthesize_speech(
        Engine="standard",
        OutputFormat="mp3",
        Text=text,
        TextType="text",
        VoiceId="Joanna",
    )
    with closing(response["AudioStream"]) as audio:
        Path(output_path).write_bytes(audio.read())


if __name__ == "__main__":
    synthesize_to_file("This is working!", "speech.mp3")
    print("Saved speech.mp3")

Run python speak.py with your AWS profile and Region configured, then play speech.mp3. If the request fails, check the selected Region, credentials, permission and voice/engine combination. Handle errors without logging private input text or credentials.

The example intentionally accepts only short plain text. For SynthesizeSpeech, AWS documents a maximum of 3,000 billed characters and 6,000 total characters per request; SSML tags count toward the total but not the billed count. The output is limited to ten minutes. See Polly quotas for current limits. For longer content, consider asynchronous speech synthesis tasks, which write output to S3; check their separate limits and supported configuration. Avoid splitting SSML or concatenating MP3 bytes without validating the resulting speech and format.

Extend the example into a serverless application

For a browser-based version, keep AWS credentials on the server. A possible architecture is:

  1. A browser sends text and an allowed voice choice to an authenticated API Gateway endpoint over HTTPS.
  2. A Lambda function validates the request, creates an owned job record in DynamoDB and starts the conversion. For longer input, it can submit a Polly speech synthesis task and record the returned task ID.
  3. A worker or status check records whether the task completed or failed. Store the audio in a private S3 bucket and associate its object key with the job and its owner.
  4. A separate authenticated endpoint checks that the caller owns the job and returns its status. Once the output is ready, it can issue a short-lived presigned S3 URL for playback or download.

Use a currently supported Python Lambda runtime and separate, least-privilege IAM roles for each function. Keep S3 Block Public Access enabled; a presigned URL is a bearer credential, so protect it and keep its lifetime short. Configure the API's authorization, request limits, CORS for your actual frontend origin, logging, error handling and cost controls before exposing the application. Do not return all users' records through a wildcard search. Plan retries and reconciliation so an uncertain task submission does not silently create duplicate billable work.

The exact deployment, frontend and asynchronous status handling depend on your application. The Python example above demonstrates the Polly request; it does not deploy the browser application. For implementation details, start with AWS's Polly API reference, Lambda Python guide, and asynchronous synthesis guide.

Conclusion

A short Polly request can produce an MP3 for an article or other text. To make this available to users, add an authenticated API, private storage and a job lifecycle that handles failure and repeated requests. Choose a voice and engine appropriate to the language and test the generated audio before using it in your application.


Explore text-to-speech APIs through Ailoot. Ailoot issues one API key for 1,284 models and variants across 15 categories, making it one of the world’s largest AI routers by model count. Use Nano Banana for photo edits, Kling for video, Scribe for audio transcription, Suno for music and Tripo3D for 3D assets. The same key works with GPT, Claude and Gemini for writing, code and document analysis.

Generate narration and speech for your app with text-to-speech APIs and Eleven v4 through Ailoot. The same key covers transcription and other media models.

Use the Ailoot API for voice features in your own paid app. Keep team access controlled and voice usage visible in the Ailoot workspace.

Ailoot adds new flagship models at launch, and one subscription covers the full catalogue. Find a promo code in your account at https://ailoot.ai/. Ailoot subscriptions and promo codes offer up to 50% off official provider API prices.