Prompt
How do I add text-to-speech to my app with an API?
Latest observation
Oct 12, 2026
OpenAI APIWeb search: off
To add text-to-speech (TTS) to your app with an API, the usual flow is:
- Send text to a TTS endpoint
- Receive audio back, usually as MP3/WAV/OGG
- Play or store that audio in your app
Basic approach
1) Pick a TTS provider
Common options:
- OpenAI TTS
- Google Cloud Text-to-Speech
- Amazon Polly
- Azure Speech
- ElevenLabs
Choose based on:
- voice quality
- supported languages/voices
- pricing
- latency
- streaming support
2) Create an API request
Most TTS APIs take:
textvoiceformatoraudio encoding- sometimes
speed,language,style
Example request shape:
{
"text": "Hello, world!",
"voice": "alloy",
"format": "mp3"
}
3) Handle the audio response
The API may return:
- raw audio bytes
- a base64-encoded string
- a URL to download the file
Then you:
- save it as a file, or
- stream it directly to the user, or
- play it in the browser/mobile app
Example: Browser playback
If your backend returns an MP3 file, your frontend can do:
const res = await fetch("/api/tts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: "Hello there!" })
});
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const audio = new Audio(url);
audio.play();
Example: Backend proxy
It’s best to call the TTS provider from your server, not directly from the client, so your API key stays secret.
Example flow:
- Frontend sends text to your backend
- Backend calls TTS provider using secret API key
- Backend returns audio to frontend
Important best practices
Security
- Never expose your TTS API key in frontend code
- Validate and limit text length to prevent abuse
Performance
- Cache repeated audio if the same text is requested often
- Use streaming if supported for faster playback
UX
- Show loading state while audio is being generated
- Add voice selection if your provider supports multiple voices
Accessibility
- TTS can help visually impaired users and support hands-free use
Minimal backend example in Node.js
Here’s the general idea:
import express from "express";
import fetch from "node-fetch";
const app = express();
app.use(express.json());
app.post("/api/tts", async (req, res) => {
const { text } = req.body;
const ttsRes = await fetch("TTS_PROVIDER_ENDPOINT", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.TTS_API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
text,
voice: "default",
format: "mp3"
})
});
const audioBuffer = await ttsRes.arrayBuffer();
res.setHeader("Content-Type", "audio/mpeg");
res.send(Buffer.from(audioBuffer));
});
app.listen(3000);
If you want, I can help you with:
- a specific provider (OpenAI, Polly, Google, Azure, ElevenLabs)
- frontend code for web or mobile
- backend code in Node, Python, or PHP
- streaming TTS instead of waiting for the full file
If you tell me your stack, I can give you a drop-in example.