DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Build a Real-Time Voice Translation App

Why Real‑Time Voice Translation Matters

In a world where borders blur and conversations flow across languages, real‑time voice translation is no longer a luxury—it's a necessity. From customer support agents speaking to clients in their native tongues, to travelers navigating foreign markets, a system that turns spoken words from one language into spoken words in another, instantly, can break down barriers that once required hours of human interpretation.

Building such an app feels like juggling three moving parts: speech‑to‑text (STT), machine translation (MT), and text‑to‑speech (TTS). Each component has its own nuances, but the real challenge is stitching them together so that the user experiences a single, fluid conversation. Below is a practical, developer‑friendly walkthrough of how to assemble these pieces using modern, open APIs and the powerful ElevenLabs TTS platform.


High‑Level Architecture

[Microphone] → [STT Engine] → [Translation Service] → [TTS Engine] → [Speaker]
Enter fullscreen mode Exit fullscreen mode
Layer Responsibility Recommended Tools
Capture Record user’s voice Web Audio API (browser)
STT Convert speech to text Web Speech API (browser) or Whisper (Python)
MT Translate text Google Cloud Translate, DeepL, or Azure Translator
TTS Speak translated text ElevenLabs (voice cloning & high‑quality synthesis)
Playback Play synthesized audio Web Audio API or <audio> tag

We’ll focus on a browser‑based prototype using JavaScript, but the same logic works in a Node.js backend or a mobile app.


Step 1 – Capture & Convert Speech to Text

Modern browsers expose the Web Speech API which gives us a quick way to turn spoken words into text. For production‑grade accuracy you might consider a paid STT service like Whisper or Google Cloud Speech-to-Text, but for a demo the browser is perfect.

// startListening.js
const startListening = (onResult) => {
  const recognition = new window.SpeechRecognition() || new window.webkitSpeechRecognition();
  recognition.lang = 'en-US';            // source language
  recognition.continuous = true;         // keep listening
  recognition.interimResults = false;    // only final results

  recognition.onresult = (event) => {
    const transcript = Array.from(event.results)
      .map(r => r[0].transcript)
      .join(' ');
    onResult(transcript);
  };

  recognition.onerror = (e) => console.error('STT error:', e);
  recognition.start();
  return recognition;
};

export default startListening;
Enter fullscreen mode Exit fullscreen mode

What it does

  • Opens the microphone.
  • Sends audio to the browser’s STT engine.
  • Returns the final transcript to a callback for the next stage.

Step 2 – Translate the Text

We���ll use the free tier of Google Cloud Translate for this demo. In a real app you’d replace this with any translation API that suits your latency and cost requirements.

// translate.js
const translateText = async (text, targetLang = 'es') => {
  const apiKey = 'YOUR_GOOGLE_API_KEY';
  const url = `https://translation.googleapis.com/language/translate/v2?key=${apiKey}`;
  const res = await fetch(url, {
    method: 'POST',
    body: JSON.stringify({
      q: text,
      target: targetLang,
    }),
    headers: { 'Content-Type': 'application/json' },
  });
  const data = await res.json();
  return data.data.translations[0].translatedText;
};

export default translateText;
Enter fullscreen mode Exit fullscreen mode

Tip: If you’re building a multilingual app, keep a mapping of language codes (en, es, fr, etc.) so you can switch on the fly.


Step 3 – Synthesize Speech with ElevenLabs

ElevenLabs offers state‑of‑the‑art TTS, including voice cloning. We’ll use their REST API to generate audio for the translated text. Replace YOUR_ELEVENLABS_API_KEY with your key from the link below.

// elevenlabs.js
const ELEVENLABS_API = 'https://api.elevenlabs.io/v1/text-to-speech';
const API_KEY = 'YOUR_ELEVENLABS_API_KEY';

export const synthesizeSpeech = async (text, voiceId = 'your-voice-id') => {
  const res = await fetch(`${ELEVENLABS_API}/${voiceId}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'xi-api-key': API_KEY,
    },
    body: JSON.stringify({
      text,
      voice_settings: {
        stability: 0.5,
        similarity_boost: 0.75,
      },
    }),
  });

  if (!res.ok) throw new Error('ElevenLabs TTS request failed');
  const arrayBuffer = await res.arrayBuffer();
  return new Blob([arrayBuffer], { type: 'audio/mpeg' });
};
Enter fullscreen mode Exit fullscreen mode

Voice Cloning

If you want the translated speech to sound like a specific person (e.g., a customer‑service rep or a brand mascot), ElevenLabs provides a voice cloning endpoint. You’ll first need to upload a short sample (≈ 30 seconds) of the target voice and receive a voice_id. Once you have it, pass that ID to the synthesizeSpeech call above.

Remember: The cloning process requires a higher-tier plan; check pricing on the ElevenLabs site.


Step 4 – Playback the Audio

We’ll stream the MP3 back to the browser and play it immediately.

// playAudio.js
export const playAudioBlob = (audioBlob) => {
  const url = URL.createObjectURL(audioBlob);
  const audio = new Audio(url);
  audio.play();
};
Enter fullscreen mode Exit fullscreen mode

Putting It All Together

Below is a minimal, end‑to‑end example that ties the four stages together. It listens to the user in English, translates to Spanish, then speaks the translation back in a cloned voice.

// index.js
import startListening from './startListening';
import translateText from './translate';
import { synthesizeSpeech } from './elevenlabs';
import { playAudioBlob } from './playAudio';

const voiceId = 'YOUR_CLONED_VOICE_ID';   // from ElevenLabs
const targetLang = 'es';                  // Spanish

const onSpeechResult = async (transcript) => {
  console.log('User said:', transcript);

  const translated = await translateText(transcript, targetLang);
  console.log('Translated:', translated);

  const audioBlob = await synthesizeSpeech(translated, voiceId);
  playAudioBlob(audioBlob);
};

const recognition = startListening(onSpeechResult);
Enter fullscreen mode Exit fullscreen mode

Run it by bundling the files with a tool like Vite or Parcel, or simply drop them into an HTML file that imports the modules. Open the page, click “Allow” when the browser asks for microphone access, and start speaking!


Handling Latency & Streaming

Real‑time translation feels natural when the round‑trip delay is under 200 ms. To reduce latency:

  1. Use WebSockets to stream STT results as they come in. The browser’s SpeechRecognition API already streams interim results; you can pipe those into translation APIs that support streaming (e.g., Google’s translateText with model='base').
  2. Chunk the translation: send short sentences or phrases instead of whole paragraphs.
  3. Cache translations for common phrases to avoid repeated API calls.
  4. Pre‑generate TTS: If you know the target language, you can pre‑synthesize “ready‑to‑play” audio for the most frequent responses.

Security & API Key Management

Never hard‑code your ElevenLabs or Google API keys in client‑side JavaScript. In production:

  • Store keys in environment variables on a server.
  • Use a lightweight backend (Node.js, Go, or Python) to proxy requests.
  • Add rate limiting and logging for audit purposes.

Scaling Up

  • Multi‑language support: Keep a mapping of langCode → voiceId for each target voice.
  • Edge deployment: Host the frontend on a CDN; run the backend on Cloudflare Workers or AWS Lambda for low‑latency.
  • Quality of Service (QoS): If your users are on flaky networks, consider buffering audio and providing a “buffering” indicator.

Final Thoughts

Building a real‑time voice translation app is a fun, rewarding challenge that brings together some of the most exciting AI technologies today. By leveraging the Web Speech API, a cloud translation service, and ElevenLabs’ high‑fidelity TTS, you can deliver a polished experience that feels almost conversational.

You’re just a few lines of code away from a prototype that can turn English into Spanish, French, or any language you choose. And if you want the voice to match your brand or a beloved persona, ElevenLabs’ voice cloning makes that possible.


Try ElevenLabs Today

Want to hear your translations in a voice that’s uniquely yours? Get started with ElevenLabs and unlock the future of conversational AI. Try ElevenLabs and turn your next app into a multilingual, voice‑first experience.

Top comments (0)