Record ten seconds of yourself talking, press a button, and hear the same sentence come back in Spanish, French or German. With a cloned voice, it comes back in yours. AssemblyAI's 2024 video tutorial, Keep Your Voice in Any Language!, built that app by chaining three vendors together. This version builds it on one API key.
A voice translator is three small jobs chained together:
- Speech-to-text: turn the recording into text.
- Translation: turn that text into the target language.
- Text-to-speech: read the translation aloud.
Here, AssemblyAI-STT-3.7-Realtime handles the first job, LLM Gateway handles the second on the same WebSocket connection, and AssemblyAI-TTS-1 handles the third. Wrap it in a Gradio app and you have a microphone button, the original transcript, the translation and an audio player, in under 300 lines of Python.
What you'll build (and the three stages)
The app takes a clip from the browser microphone, streams it to AssemblyAI, and gets two things back on one connection: the transcript of each turn, and its translation. Then it sends the translation to text-to-speech and plays the WAV file.
| Stage | AssemblyAI product | Model ID | Billing basis |
|---|---|---|---|
| Speech-to-text | AssemblyAI-STT-3.7-Realtime (streaming API) | assemblyai-stt-3-7-realtime |
$0.30 per hour of session time |
| Translation | LLM Gateway, through the llm_gateway connection parameter |
qwen3.5-4b-32k-fast (any Gateway model works) |
Per token, at the rate of the model you choose |
| Text-to-speech | AssemblyAI-TTS-1 | assemblyai-tts-1 |
$15 per 1M characters |
Why a streaming model for a recorded clip? Because the real-time translation feature lives on the streaming API. You set one connection parameter, and every time a turn ends the server sends the transcript to LLM Gateway with your prompt and returns the translation on the same WebSocket. There's no upload, no polling and no second API to call. It also means the live version of this app, covered at the end, is the same code with a microphone in place of the clip.
AssemblyAI has two 3.7 streaming models. AssemblyAI-STT-3.7-Realtime-Agent ($0.45/hr) is built for voice agents, where software answers the speaker. A translator only listens and repeats, so this build uses AssemblyAI-STT-3.7-Realtime ($0.30/hr), the model the docs recommend for notetakers and ambient transcription. Both support real-time translation.
What you'll need
- An AssemblyAI API key. Copy it from your dashboard.
- Python 3.10 or later. Gradio needs 3.10. The AssemblyAI Python SDK 1.10.1 is the release that includes the STT 3.7 model IDs, and text-to-speech has been in the SDK since 1.8.2.
- Optional: a cloned voice. If you want the translation spoken in your own voice, create a clone in the dashboard first. Step 3 covers it.
Clone the companion repo, or create the files as you go:
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install assemblyai==1.10.1 gradio numpy python-dotenv
echo "ASSEMBLYAI_API_KEY=your-api-key" > .envThe code reads the key from the environment, so it never sits in a source file.
Step 1: prepare the clip for AssemblyAI-STT-3.7-Realtime
The streaming API takes raw 16-bit PCM. Gradio's microphone hands you a sample rate and a NumPy array, usually at 44.1 or 48 kHz and sometimes in stereo, so the first job is to convert it to 16 kHz mono. NumPy's linear interpolation is good enough for speech and saves you an ffmpeg dependency.
Put this at the top of translator.py:
import os
import tempfile
import threading
import time
import assemblyai as aai
import numpy as np
from assemblyai.streaming.v3 import (
LLMGatewayResponseEvent,
RealTimeError,
RealTimeEvents,
RealTimeParameters,
RealTimeTranscriber,
RealTimeTranscriberOptions,
TurnEvent,
)
from assemblyai.streaming.v3.models import LLMGatewayConfig, LLMGatewayMessage
STT_MODEL = "assemblyai-stt-3-7-realtime"
TRANSLATION_MODEL = "qwen3.5-4b-32k-fast"
SAMPLE_RATE = 16000
CHUNK_MS = 50
MAX_CLIP_SECONDS = 120
TRANSLATION_TIMEOUT_S = 10
def api_key() -> str:
key = os.environ.get("ASSEMBLYAI_API_KEY")
if not key:
raise RuntimeError("Set ASSEMBLYAI_API_KEY in your environment or .env file.")
return key
def to_pcm16(sample_rate: int, samples: np.ndarray) -> bytes:
"""Convert a Gradio (sample_rate, numpy array) clip to 16 kHz mono 16-bit PCM."""
samples = np.asarray(samples)
if samples.ndim == 2: # stereo -> mono
samples = samples.mean(axis=1)
if np.issubdtype(samples.dtype, np.integer):
samples = samples.astype(np.float32) / 32768.0
else:
samples = samples.astype(np.float32)
if sample_rate != SAMPLE_RATE:
duration = len(samples) / sample_rate
target_len = int(duration * SAMPLE_RATE)
old_t = np.linspace(0.0, duration, num=len(samples), endpoint=False)
new_t = np.linspace(0.0, duration, num=target_len, endpoint=False)
samples = np.interp(new_t, old_t, samples)
samples = np.clip(samples, -1.0, 1.0)
return (samples * 32767).astype("<i2").tobytes()
def paced_chunks(pcm: bytes):
"""Yield 50 ms chunks at real-time pace, the way a microphone would."""
step = SAMPLE_RATE * 2 * CHUNK_MS // 1000
for start in range(0, len(pcm), step):
yield pcm[start : start + step]
time.sleep(CHUNK_MS / 1000)paced_chunks() sends the clip in 50 ms pieces at the speed a microphone would, so a 10-second clip takes about 10 seconds to stream. That keeps the session behaving exactly as it will when you switch to live audio. MAX_CLIP_SECONDS caps a clip at two minutes, which also keeps the translation well under TTS-1's 5,000-character limit per request.
Transcription, translation through LLM Gateway, and text-to-speech all run on one AssemblyAI API key. Sign up and run the voice translator on your own voice in a few minutes.
Step 2: transcribe and translate on one WebSocket with LLM Gateway
This is the core of the app. Open a streaming session with speech_model="assemblyai-stt-3-7-realtime" and an llm_gateway object that holds the translation prompt. The server transcribes the audio and, each time a turn ends, sends that turn to LLM Gateway with your prompt. The translation comes back as an LLMGatewayResponse message with the same turn_order as the transcript it came from.
# {{history_3}} and {{turn}} are filled in by the server for every final turn.
# Leave them exactly as written. TARGET is replaced in build_prompt().
PROMPT_TEMPLATE = (
"You are translating a short voice recording into TARGET.\n"
"Earlier in the recording: {{history_3}}\n\n"
"Translate the next turn from whatever language is spoken into natural TARGET. "
"Reply with only the TARGET translation of this turn, with no preamble: {{turn}}"
)
def build_prompt(target_language: str) -> str:
return PROMPT_TEMPLATE.replace("TARGET", target_language.capitalize())
def transcribe_and_translate(pcm: bytes, target_language: str) -> tuple[str, str]:
"""Stream a clip through STT-3.7-Realtime and return (transcript, translation)."""
finals: dict[int, str] = {}
translations: dict[int, str] = {}
open_turns: set[int] = set()
errors: list[str] = []
changed = threading.Condition()
def on_turn(client, event: TurnEvent):
with changed:
if not event.end_of_turn:
if event.transcript.strip():
open_turns.add(event.turn_order)
return
open_turns.discard(event.turn_order)
if event.transcript.strip(): # noise can produce an empty final
finals[event.turn_order] = event.transcript
changed.notify_all()
def on_translation(client, event: LLMGatewayResponseEvent):
text = event.data["choices"][0]["message"]["content"].strip()
with changed:
translations[event.turn_order] = text
changed.notify_all()
def on_error(client, error: RealTimeError):
with changed:
errors.append(str(error))
changed.notify_all()
client = RealTimeTranscriber(
RealTimeTranscriberOptions(api_key=api_key(), api_host="streaming.assemblyai.com")
)
client.on(RealTimeEvents.Turn, on_turn)
client.on(RealTimeEvents.LLMGatewayResponse, on_translation)
client.on(RealTimeEvents.Error, on_error)
client.connect(
RealTimeParameters(
sample_rate=SAMPLE_RATE,
speech_model=STT_MODEL,
llm_gateway=LLMGatewayConfig(
model=TRANSLATION_MODEL,
messages=[LLMGatewayMessage(role="user", content=build_prompt(target_language))],
max_tokens=400,
),
)
)
try:
client.stream(paced_chunks(pcm))
time.sleep(0.3) # let the last audio reach the server
client.force_endpoint() # end the last turn now instead of waiting for silence
def done() -> bool:
return bool(errors) or (not open_turns and set(finals) <= set(translations))
with changed:
changed.wait_for(done, timeout=TRANSLATION_TIMEOUT_S)
finally:
client.disconnect(terminate=True)
if errors:
raise RuntimeError(f"Streaming error: {errors[0]}")
order = sorted(finals)
transcript = " ".join(finals[i] for i in order)
# A turn whose gateway call failed has no translation; skip it.
translation = " ".join(translations[i] for i in order if i in translations)
return transcript, translationA few details in there are worth knowing before you change anything:
- The prompt is a template. The server replaces
{{turn}}with the final transcript of each turn and{{history_3}}with up to three earlier turns, so leave both exactly as written. History is what lets "Yes, that one." translate correctly. The prompt asks for the translation only, with no preamble, which keeps the model from adding "Here is your translation:" to the audio. - Any source language works. STT-3.7-Realtime is multilingual by default and handles code switching with no language parameter. Because the prompt says "from whatever language is spoken", you can talk in any of the 32 languages it transcribes.
- Pick a small model.
qwen3.5-4b-32k-fastis the model in the docs example, and with a small model like it the translation typically lands within about 100 ms of the final turn. Leavemodelout and you getgemini-2.5-flash-lite. Any model on the Available models list works, andmax_tokens=400is plenty for one turn. - Only final turns are translated. Partial transcripts stay in the spoken language. Translations are produced in the background, so two short turns can come back out of order. Joining by
turn_orderfixes that. - End the last turn yourself. When the clip ends, the speaker has probably stopped mid-pause, and the server would otherwise wait for more silence.
force_endpoint()sendsForceEndpoint, which ends the turn in progress right away. The function then waits until every non-empty turn has its translation, up to 10 seconds, because a failed or timed-out gateway call sends no response for that turn. - Noise can produce an empty final turn. The handler skips those, so they don't hold up the wait.
If your clips are full of names, product terms or jargon, pass keyterms_prompt=["..."] in RealTimeParameters. Both STT 3.7 realtime models support keyterm prompting, and a name spelled right in stage one is a name translated right in stage two.
Step 3: speak the translation with AssemblyAI-TTS-1
TTS-1 speaks six languages: English, Spanish, French, German, Italian and Portuguese. That's why this translator offers those six targets and drops the Russian, Turkish, Swedish and Japanese outputs from the 2024 version.
Every language has a default AssemblyAI voice, recorded in that language. The Voices docs list them, and the code below names each one explicitly so the voice doesn't change if a default does:
# The default AssemblyAI voice for each language TTS-1 speaks
# (https://www.assemblyai.com/docs/tts/voices#the-default-voice).
VOICES = {
"english": "aai-kyla",
"spanish": "aai-antonioluis",
"french": "aai-donatien",
"german": "aai-magdalena",
"italian": "aai-giada",
"portuguese": "aai-nelson",
}
def speak(text: str, language: str, voice_id: str | None = None) -> str:
"""Speak text with AssemblyAI TTS-1 and return the path of a WAV file."""
config = aai.TTSConfig(
voice_id=voice_id or VOICES[language],
language=language,
container=aai.TTSContainer.wav,
)
response = aai.TextToSpeech(api_key=api_key()).synthesize(text, config)
fd, path = tempfile.mkstemp(suffix=".wav")
with os.fdopen(fd, "wb") as f:
f.write(response.audio)
return pathTwo things to know about the request. language takes the full English name of the language (spanish), not an ISO code like es, which is different from the STT APIs. And container=aai.TTSContainer.wav returns a WAV file with a header, so Gradio can play the path directly. The response also carries billed_characters and audio_duration_ms if you want to log cost per clip.
Use your own cloned voice
To hear the translation in your own voice, clone it in the voice catalog in the AssemblyAI dashboard. Voice cloning takes 10 to 30 seconds of one person speaking. You attest that the speaker consented, and your account has to accept the biometric data terms first. Copy the voice ID and pass it as voice_id.
Three limits apply:
- A cloned voice can be used for 60 days after its consent was last given, unless you renew the consent before then.
- A clone belongs to the data zone it was created in. This app calls the US host, so create the voice in the US zone.
- The docs warn that a voice usually sounds best in its own language. Your English clone speaking Spanish will sound like you, with lower quality than in English, and that's the main tradeoff of this demo.
Step 4: wire it into Gradio
translate_clip() is the function Gradio calls. It checks the clip, runs stages one and two, and sends the translation to TTS-1:
def translate_clip(clip, target_language: str, voice_id: str | None = None):
"""Gradio entry point: (sample_rate, samples) -> (transcript, translation, wav path)."""
if clip is None:
raise ValueError("Record or upload a clip first.")
sample_rate, samples = clip
if len(samples) / sample_rate > MAX_CLIP_SECONDS:
raise ValueError(f"Keep clips under {MAX_CLIP_SECONDS} seconds.")
language = target_language.lower()
transcript, translation = transcribe_and_translate(to_pcm16(sample_rate, samples), language)
if not translation:
return transcript, "", None
return transcript, translation, speak(translation, language, voice_id or None)The simplest app is a gr.Interface with one input and three outputs. Save it as simple_translator.py:
"""Record a clip, hear it back in Spanish."""
import gradio as gr
from dotenv import load_dotenv
from translator import translate_clip
load_dotenv()
def translate_to_spanish(clip):
return translate_clip(clip, "spanish")
demo = gr.Interface(
fn=translate_to_spanish,
inputs=gr.Audio(sources=["microphone", "upload"], type="numpy", label="Speak"),
outputs=[
gr.Textbox(label="What you said"),
gr.Textbox(label="Spanish"),
gr.Audio(type="filepath", label="Spanish audio"),
],
title="AI voice translator",
description="Speak in any language STT-3.7-Realtime supports and hear it in Spanish.",
)
if __name__ == "__main__":
demo.launch()type="numpy" makes Gradio pass (sample_rate, samples) to your function, which is what to_pcm16() expects. Adding "upload" to sources lets you drop in an audio file as well as record one.
Run it with python simple_translator.py, open the local URL, allow microphone access and record a sentence. While you're iterating, run gradio simple_translator.py instead. Gradio then watches the file and reloads the app every time you save.
The gr.Blocks version: six languages and your own voice
gr.Blocks gives you control over the layout. This version adds a dropdown for the target language and a text field for a cloned voice ID, and shows the transcript and translation next to the audio. Save it as voice_translator.py:
"""Pick a target language and, optionally, your own cloned voice."""
import os
import gradio as gr
from dotenv import load_dotenv
from translator import VOICES, translate_clip
load_dotenv()
LANGUAGES = [name.capitalize() for name in VOICES] # the six languages TTS-1 speaks
with gr.Blocks(title="AI voice translator") as demo:
gr.Markdown("## AI voice translator\nSpeak, pick a language, and hear the translation.")
with gr.Row():
with gr.Column():
clip = gr.Audio(sources=["microphone", "upload"], type="numpy", label="Speak")
target = gr.Dropdown(LANGUAGES, value="Spanish", label="Translate into")
voice = gr.Textbox(
value=os.environ.get("ASSEMBLYAI_VOICE_ID", ""),
label="Voice ID (optional)",
placeholder="Blank = the language's default voice, or paste a cloned voice ID",
)
button = gr.Button("Translate", variant="primary")
with gr.Column():
transcript = gr.Textbox(label="What you said")
translation = gr.Textbox(label="Translation")
audio = gr.Audio(type="filepath", label="Translated audio")
button.click(
fn=translate_clip,
inputs=[clip, target, voice],
outputs=[transcript, translation, audio],
)
if __name__ == "__main__":
demo.launch()Leave the voice field blank and each language uses its default voice. Paste a cloned voice ID, or set ASSEMBLYAI_VOICE_ID in .env, and every language is spoken in that voice.
Why a dropdown and not one audio player per language? The llm_gateway prompt is set when the session opens, so each target language is its own streaming session. Translating into five languages at once would mean five sessions for the same clip. If you want that, call translate_clip() once per language in a loop, and expect the run to take five times as long.
Try voices in all six languages in the playground before you pick one for your translator, then clone your own in the dashboard.
Make it live: translate while you speak
This app waits for you to stop talking. To translate as you speak, keep the same llm_gateway session and replace paced_chunks() with a generator that reads 50 ms frames from the microphone. Translations then arrive turn by turn while you talk, and you can speak each one over a single TTS-1 WebSocket session that stays open for the whole conversation, which avoids a new connection handshake for every sentence.
The real-time speech translation tutorial builds that version step by step. If you're choosing between providers for live translation, the best real-time speech translation APIs compares them, and speech-to-speech for voice agents covers the cascaded pipeline from the voice agent side.
Where errors compound, and why stage one matters
Build this and run it a few times, and one thing becomes obvious: errors only travel downstream. A misheard word in stage one becomes a wrong phrase in stage two, and then text-to-speech says it clearly and confidently, possibly in your own voice. Nothing after transcription can recover a word the transcript got wrong.
So spend your accuracy budget on stage one. Use the keyterm list for names and product terms. Keep {{history_3}} in the prompt so short turns get context. And check the transcript box in the app before you blame the translation, because a bad translation of a correct transcript is a prompt or model problem, while a bad translation of a wrong transcript starts at the microphone.
The same three-stage shape shows up well beyond this demo. Swap the translation prompt for a reply prompt and you have the real-time AI voice bot in Python. For the full picture of what AssemblyAI translates, in real time and in batch, see the translation feature page, and for other voices to compare, the top text-to-speech APIs.
Transcribe with AssemblyAI-STT-3.7-Realtime, translate with LLM Gateway, and speak with AssemblyAI-TTS-1. Start with a free account.
Frequently Asked Questions (FAQs)
Is there an AI voice translator that can translate speech in real time?
Yes. AssemblyAI's streaming API translates each finished turn on the same WebSocket that transcribes it, through the llm_gateway connection parameter, and with a small model the translation typically arrives within about 100 ms of the final turn. Add AssemblyAI-TTS-1 on a long-lived WebSocket session to speak each translation as it arrives. The real-time translation docs have the full reference.
How do I translate speech to another language in Python?
Install the assemblyai Python SDK, open a streaming session with an llm_gateway object that holds your translation prompt, and stream 16 kHz PCM audio to it. Each final turn returns an LLMGatewayResponse whose data["choices"][0]["message"]["content"] is the translation. Match it to the transcript by turn_order.
Can the translated audio sound like my own voice?
Yes. Clone your voice in the AssemblyAI dashboard from 10 to 30 seconds of speech, then pass its voice ID as voice_id to AssemblyAI-TTS-1. The clone needs the speaker's consent, stays usable for 60 days unless you renew that consent, and usually sounds best in the language you recorded it in.
Which languages can an AssemblyAI voice translator speak?
AssemblyAI-TTS-1 speaks six languages: English, Spanish, French, German, Italian and Portuguese, each with a default AssemblyAI voice. The input side is broader, because AssemblyAI-STT-3.7-Realtime transcribes 32 languages with native code switching, and the translation prompt can take any of them.
How much does it cost to run an AI voice translator?
You pay for three things: AssemblyAI-STT-3.7-Realtime at $0.30 per hour of streaming session time, LLM Gateway tokens at the rate of the model you choose, and AssemblyAI-TTS-1 at $15 per 1M characters. A 10-second clip with a one-sentence translation costs a fraction of a cent.
Do I need a separate translation API?
No. On the streaming API, translation runs through LLM Gateway on the same connection as transcription, so there's no second service, key or request. For pre-recorded files, AssemblyAI also offers translation as part of the transcription request, billed as a $0.06/hr add-on.