Prompt
How do I make a browser app read text aloud using an API?
Latest observation
Oct 15, 2026
OpenAI APIWeb search: off
You can make a browser app read text aloud by sending the text to a text-to-speech API, then playing the returned audio in the browser.
Basic flow
- User enters text.
- Your app sends that text to a TTS API.
- API returns audio data or an audio URL.
- Browser plays the audio with an
<audio>element or Web Audio API.
Example: using a generic TTS API
HTML
<textarea id="text">Hello world</textarea>
<button id="speak">Speak</button>
<audio id="player" controls></audio>
JavaScript
document.getElementById("speak").addEventListener("click", async () => {
const text = document.getElementById("text").value;
const response = await fetch("https://api.example.com/tts", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY"
},
body: JSON.stringify({
text: text,
voice: "en-US"
})
});
if (!response.ok) {
console.error("TTS request failed");
return;
}
// If API returns audio as a file/blob
const audioBlob = await response.blob();
const audioUrl = URL.createObjectURL(audioBlob);
const player = document.getElementById("player");
player.src = audioUrl;
player.play();
});
If the API returns a URL instead of raw audio
Some APIs return JSON like:
{ "audioUrl": "https://..." }
Then do:
const data = await response.json();
const player = document.getElementById("player");
player.src = data.audioUrl;
player.play();
If you don’t need an external API
Browsers also have built-in speech synthesis:
const utterance = new SpeechSynthesisUtterance("Hello world");
speechSynthesis.speak(utterance);
This is easier, but voices and quality depend on the browser/device.
Important notes
- Don’t expose secret API keys in frontend code if the service requires a private key. Use a backend proxy.
- Handle autoplay restrictions: browsers often require a user click before audio can play.
- For long text, you may need to split it into chunks depending on API limits.
Recommended architecture
Frontend
- Collect text
- Send request to your backend
Backend
- Calls the TTS provider securely
- Returns audio or a signed URL
If you want, I can show you:
- a full example with a real TTS API,
- a version using only browser built-in speech synthesis, or
- a secure frontend + backend setup.