Prompt
How do I add text-to-speech to my app with an AI API?
Latest observation
Nov 21, 2026
OpenAI APIWeb search: off
You can add text-to-speech (TTS) to your app by sending text to an AI TTS API, receiving audio back, and playing or saving that audio in your app.
Basic flow
- User enters text
- Your backend sends that text to the AI TTS endpoint
- The API returns audio data or an audio file URL
- Your app plays the audio
What you need
- An API key from the AI provider
- A server/backend to keep the key secret
- A way to play audio in your app:
- Web:
<audio>element or Web Audio API - Mobile: platform audio player
- Desktop: native audio library
- Web:
Typical API request
Most TTS APIs work like this:
text: the content to speakvoice: which voice to useformat: mp3, wav, opus, etc.- optional settings:
- speed
- pitch
- language
- style/emotion
Example conceptually
POST /tts
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
{
"text": "Hello world",
"voice": "alloy",
"format": "mp3"
}
The response is usually:
- binary audio data, or
- a JSON object with a signed download URL
Simple web example
If the API returns an audio file, you can play it like this:
<audio id="player" controls></audio>
<script>
async function speak(text) {
const res = await fetch("/api/tts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text })
});
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const player = document.getElementById("player");
player.src = url;
player.play();
}
</script>
Backend example
Your backend calls the TTS API and streams the audio back to the client:
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("https://api.example.com/tts", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
text,
voice: "alloy",
format: "mp3"
})
});
res.setHeader("Content-Type", "audio/mpeg");
ttsRes.body.pipe(res);
});
app.listen(3000);
Important best practices
- Never expose your API key in frontend code
- Validate and limit text length
- Handle latency/loading states
- Cache repeated audio if needed
- Consider streaming if you want faster playback
- Check licensing/commercial usage rights for voices
If you want the best user experience
- Use short prompts for faster responses
- Stream audio if the API supports it
- Pre-generate audio for common phrases
- Add voice selection in settings
- Fall back gracefully if TTS fails
If you want, I can help with:
- a specific AI API like OpenAI, Google, Azure, or ElevenLabs
- JavaScript/React, Python, iOS, or Android code
- streaming TTS
- speech-to-speech or voice cloning
If you tell me your platform and which API you want to use, I can give you a ready-to-run example.