Real-time Indian Language Text-to-Speech for Web Apps
In this article
Yes, you can build real‑time Indian language text‑to‑speech into a web app by combining the Web Speech API (or a cloud TTS service) with JavaScript and a lightweight backend.
This guide shows you how to set up a multilingual TTS pipeline that works instantly in the browser, supports major Indian languages, and can be expanded to any language supported by the chosen service.
What You’ll Need
- A modern web browser that supports the Web Speech API (Chrome, Edge, or Safari)
- Basic knowledge of HTML, CSS, and JavaScript
- An account with a cloud TTS provider that offers Indian languages (e.g., Google Cloud Text‑to‑Speech, Amazon Polly, Microsoft Azure Speech)
- Node.js installed locally (for the optional backend)
- SSL‑enabled hosting (HTTPS) – required for most browser speech APIs
Step‑by‑Step
- Choose the speech engine. For quick prototyping use the browser’s built‑in
speechSynthesisinterface. For higher quality voices or server‑side control, sign up for a cloud provider and enable the Indian language voices you need (Hindi, Bengali, Tamil, Telugu, Marathi, etc.). - Create a simple HTML page. Add a text area for input, a dropdown to select the language, and a button to start playback.
<textarea id="text" rows="4" cols="50" placeholder="Enter text"></textarea> <select id="lang"> <option value="hi-IN">Hindi</option> <option value="ta-IN">Tamil</option> <option value="te-IN">Telugu</option> <option value="bn-IN">Bengali</option> </select> <button id="speak">Speak</button> - Implement client‑side synthesis with the Web Speech API. Attach a click handler that creates a
SpeechSynthesisUtterance, setslangto the selected value, and callsspeechSynthesis.speak().document.getElementById('speak').addEventListener('click', () => { const text = document.getElementById('text').value.trim(); if (!text) return; const lang = document.getElementById('lang').value; const utter = new SpeechSynthesisUtterance(text); utter.lang = lang; // Optional: pick a voice that matches the language const voice = speechSynthesis.getVoices().find(v => v.lang === lang); if (voice) utter.voice = voice; speechSynthesis.speak(utter); });Note:
speechSynthesis.getVoices()may return an empty array on first call; call it after a shortsetTimeoutor on thevoiceschangedevent. - Test locally. Serve the page over HTTPS (e.g.,
npm i -g serve && serve -s .) and open it in Chrome. The selected voice should read the text instantly. - Add a fallback to a cloud TTS service. If the browser lacks a high‑quality voice for a language, call your backend to fetch an audio file.
- Set up a Node.js Express endpoint
/ttsthat receivestextandlangvia POST. - Inside the handler, call the provider’s SDK (e.g.,
@google-cloud/text-to-speech) with the appropriatelanguageCodeandvoiceparameters. - Return the audio content as a base64‑encoded MP3.
app.post('/tts', async (req, res) => { const {text, lang} = req.body; const request = { input: {text}, voice: {languageCode: lang, ssmlGender: 'NEUTRAL'}, audioConfig: {audioEncoding: 'MP3'} }; const [response] = await client.synthesizeSpeech(request); res.json({audioContent: response.audioContent.toString('base64')}); });
- Set up a Node.js Express endpoint
- Play the streamed audio. In the client, fetch the endpoint, convert the base64 string to a Blob, and feed it to an
HTMLAudioElement.async function speakViaCloud(text, lang) { const resp = await fetch('/tts', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({text, lang}) }); const data = await resp.json(); const audio = new Audio('data:audio/mp3;base64,' + data.audioContent); audio.play(); }Use this path when
speechSynthesisreportsutterance.erroror when the selected language is not listed. - Implement real‑time streaming (optional). For truly live feedback, split the input into sentences or phrases and send each chunk to the backend as the user types. Append each returned audio chunk to a
MediaSourcebuffer so playback continues without gaps.Because most cloud APIs have a minimum text length, batch at least 30‑50 characters per request to stay within quota limits.
- Deploy. Host the static files on any HTTPS‑enabled service (GitHub Pages, Netlify, Vercel). Deploy the Node.js backend on a platform that supports HTTPS (Render, Railway, Heroku). Ensure API keys are stored in environment variables, never in client‑side code.
Common Mistakes
- Attempting to use
speechSynthesison an insecure (http) page – browsers block the API. - Choosing a language code that does not match any installed voice; the utterance will be silent.
- Calling
speechSynthesis.speak()before the voice list is populated – results in the default voice being used. - Embedding API keys in JavaScript; this exposes them to anyone who inspects the page.
- Sending overly long text in a single cloud request – many providers truncate or reject it.
Tips
- Cache the list of available voices on page load and reuse it for every request.
- Provide a small “Test” button that reads a preset sentence in each language so users can verify their speaker settings.
- Use
navigator.languageto pre‑select the most likely language for the user. - When using cloud TTS, enable
speakingRateandpitchadjustments to match natural conversation speed. - Compress the returned MP3 with
audio/mp3and set theCache-Controlheader to improve repeat‑play performance.
Troubleshooting
- No sound at all. Verify the page is served over HTTPS. Open the browser console and look for “NotAllowedError” – that indicates a permission issue.
- Wrong voice or language. Check the
langattribute on the utterance matches a voice’slang. UsespeechSynthesis.getVoices()in the console to see what the browser reports. - Audio cuts off after a few seconds. This often happens when the
SpeechSynthesisUtteranceis garbage‑collected. Keep a reference to the utterance untilonendfires. - Cloud endpoint returns 401/403. Ensure your API key is valid, has the correct IAM permissions, and is sent only from the server side.
- Playback latency. If the cloud response takes more than a second, pre‑fetch the audio for common phrases or use a local cache for repeated text.
- Browser does not list Indian voices. Update the browser to the latest version or install the language pack in the OS settings (e.g., Windows Settings > Time & Language > Language > Add a language).
Frequently Asked Questions
Can I use the Web Speech API for all Indian languages?
The API supports any language for which the underlying OS provides a voice. Hindi, Tamil, Telugu, Malayalam, Bengali, Marathi, and Gujarati are commonly available, but less‑used languages may not appear.
Do I need a paid cloud account for high‑quality voices?
Free tiers usually allow a limited number of characters per month. For production‑level quality and larger volumes you will need a paid plan, but the code works the same way.
Is it possible to stream audio while the user is still typing?
Yes. Split the input into short chunks (30–50 characters) and send each chunk to the backend as soon as it is entered. Append the returned audio to a MediaSource buffer to achieve seamless playback.
How do I protect my API key from being stolen?
Never expose the key in client‑side JavaScript. Store it in an environment variable on the server and let the server act as a proxy for the TTS request.
Will this work on mobile browsers?
Modern mobile browsers that support the Web Speech API (Chrome Android, Safari iOS) will handle the client‑side path. For cloud fallback, ensure the backend is reachable over HTTPS; mobile devices treat it the same as desktop browsers.
Can I change the voice speed or add pauses?
When using speechSynthesis, adjust utterance.rate (0.5–2.0). For cloud services, set speakingRate in the request payload, and you can embed SSML tags like <break time="200ms"/> in the text.