Speech-to-Text and Text-to-Speech: Model Runs, Gateway Routes, and Live Audio
How to run Cloudflare Workers AI STT and TTS models, route speech through AI Gateway, and stream live transcription or synthesis.
This page summarises Cloudflare documentation on running speech-to-text (STT) and text-to-speech (TTS) from a Worker with the AI binding, optionally through AI Gateway for logging, provider keys, and WebSocket streaming. The same patterns cover batch transcription from a URL or file, synthesised speech returned as audio URLs or raw PCM, and low-latency microphone or telephony flows.
env.AI.run: how to call a speech model from a Worker
Section titled “env.AI.run: how to call a speech model from a Worker”Speech models on Workers AI are invoked like any other model: env.AI.run(modelId, input) inside a Worker, or the REST equivalent POST https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run with a Bearer token.
const response = await env.AI.run( ‘assemblyai/universal-3-pro’, { audio_url: ‘https://cdn.openai.com/API/docs/audio/alloy.wav’ }, ) console.log(response)
— Cloudflare, AssemblyAI Universal-3 Pro
Gateway-routed models often return a envelope with state, result, and gatewayMetadata (for example keySource: "Unified"). STT results typically include text and may include per-word timings; TTS results often expose an audio URL or inline data.
STT vs TTS inputs (what you pass in)
Section titled “STT vs TTS inputs (what you pass in)”| Task | Typical input fields |
Example model IDs in the docs |
|---|---|---|
| Transcribe remote audio | audio_url, url |
assemblyai/universal-3-pro, assemblyai/universal-3.5-pro, xai/grok-stt |
| Transcribe uploaded audio | file (data URI), audio (bytes/base64) |
openai/gpt-4o-transcribe, xai/grok-stt, @cf/openai/whisper |
| Synthesise speech | text, plus voice/format options |
elevenlabs/eleven-flash-v2-5, openai/tts-1, google/gemini-3.8-flash-tts |
| Raw audio HTTP response (TTS) | text with returnRawResponse: true |
@cf/deepgram/aura-1 |
Speech-to-text models: when to use which option
Section titled “Speech-to-text models: when to use which option”AssemblyAI via Workers AI
Section titled “AssemblyAI via Workers AI”assemblyai/universal-3-pro and assemblyai/universal-3.5-pro take an audio_url and return rich transcripts: full text, confidence, language_code, and a words array with start, end, and per-word confidence.
universal-3.5-pro additionally supports steering transcription with language_code and domain terms via keyterms_prompt, as in the Universal-3.5 Pro examples. Use this when jargon or product names must be spelled correctly.
OpenAI-family transcription
Section titled “OpenAI-family transcription”openai/gpt-4o-transcribe—fileas adata:audio/wav;base64,...URI; optionallanguage,prompt(context for style and vocabulary), andtemperature. Documented in GPT-4o Transcribe.@cf/openai/whisper— accepts anaudiobyte array (for example after Media Transformations extract audio from video). The binding response includestext,word_count,vtt, andwords. See Bind to Workers API — transcribe with Media Transformations and the Jupyter notebook Whisper example.
Extract audio, then transcribe using Whisper on Workers AI.
— Cloudflare, Bind to Workers API
For long files, the Whisper-large-v3-turbo chunking tutorial fetches audio from a URL, splits it into chunks (for example 1 MB), runs @cf/openai/whisper-large-v3-turbo per chunk, and concatenates text. That fits batch jobs where a single request would exceed model limits.
xAI Grok STT
Section titled “xAI Grok STT”xai/grok-stt accepts url or file, and optional language, format (inverse text normalisation), diarize, keyterm, and filler_words. Responses include duration and timed words, with optional speaker labels when diarize: true. Details: Grok STT.
Text-to-speech models: voices, formats, and raw audio
Section titled “Text-to-speech models: voices, formats, and raw audio”Most TTS models follow env.AI.run(modelId, { text, ...voiceAndFormat }) and return result.audio as a hosted URL (ElevenLabs, OpenAI, Inworld, MiniMax, xAI) or audio inline (some Gemini responses use data:audio/l16;base64,... per Gemini 3.1 Flash TTS).
| Provider (via Workers AI) | Notable parameters | Doc anchor |
|---|---|---|
ElevenLabs (eleven-flash-v2.5, eleven-turbo-v2.5, eleven-multilingual-v2, eleven-v3) |
voice_id, output_format (e.g. mp3_44100_128), language_code on multilingual |
Eleven Flash v2.5 |
OpenAI (openai/tts-1, openai/tts-1-hd) |
voice, response_format, speed |
TTS-1 |
Google Gemini (google/gemini-3.8-flash-tts, lite variants) |
voice; markup like `<short pause>` in 3.8 |
Gemini 3.8 Flash TTS |
Deepgram (@cf/deepgram/aura-1) |
returnRawResponse: true for direct audio HTTP body |
aura-1 |
Inworld (inworld/tts-2, tts-1.5-max, etc.) |
voice_id, speaking_rate, sample_rate, bracket steering [whisper] |
Inworld TTS 2 |
MiniMax (minimax/speech-2.8-hd, turbo) |
emotion, speed, pitch, sample_rate |
MiniMax Speech 2.8 HD |
xAI (xai/grok-tts) |
text, language |
Grok TTS |
export default { async fetch(request, env, ctx): Promise<Response> { const resp = await env.AI.run(“@cf/deepgram/aura-1”, { “text”:“Hello World!” }, { returnRawResponse: true }); return resp; }, } satisfies ExportedHandler<Env>;
— Cloudflare, @cf/deepgram/aura-1
Use returnRawResponse: true when the Worker must stream bytes to the client without wrapping JSON.
AI Gateway: provider-native HTTP and WebSocket speech routes
Section titled “AI Gateway: provider-native HTTP and WebSocket speech routes”AI Gateway sits in front of third-party APIs and Workers AI. For batch TTS with your own provider key, you can call gateway URLs directly—for example Cartesia TTS bytes or ElevenLabs text-to-speech.
For live STT, the Realtime WebSockets API — Speech-to-Text documents microphone streaming to Workers AI Deepgram models:
Workers AI supports two Deepgram STT models:
@cf/deepgram/nova-3and@cf/deepgram/flux.— Cloudflare, Realtime WebSockets API
Connect with query parameters such as encoding=linear16, sample_rate=16000, and interim_results=true, send raw audio frames on the socket, and read channel.alternatives[0].transcript with is_final for partial vs final text.
For live TTS on the same page, Deepgram @cf/deepgram/aura-1 accepts JSON messages {"type":"Speak","text":"..."} and {"type":"Flush"}; audio arrives as binary frames and metadata as JSON (Metadata, Flushed, etc.).
The Deepgram AI Gateway SDK example shows live transcription through wss://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/deepgram/ with cf-aig-authorization and the Deepgram client’s listen.live API (model: "nova-3", smart_format: true).
xAI Grok Voice (bidirectional WebSocket)
Section titled “xAI Grok Voice (bidirectional WebSocket)”xai/grok-voice uses a WebSocket upgrade on the Workers AI run endpoint; clients send input_audio_buffer.append with base64 audio and receive messages for transcription and synthesized replies. See Grok Voice. Plain curl cannot complete the upgrade; use wscat or a WebSocket library as noted in that doc.
End-to-end patterns: video, telephony, and Realtime SFU
Section titled “End-to-end patterns: video, telephony, and Realtime SFU”Video file to transcript in one Worker
Section titled “Video file to transcript in one Worker”Pipeline: load video (R2 or fetch) → env.MEDIA.input(...).transform().output({ mode: 'audio' }) → pass audio bytes to @cf/openai/whisper. Documented in Bind to Workers API. This avoids storing a separate audio file when you only need text.
Telephony and PCM constraints
Section titled “Telephony and PCM constraints”For voice agents on Twilio or Plivo, Voice — PCM output for telephony states that Workers AI TTS that returns MP3 cannot be decoded to PCM in the Workers runtime, so telephony adapters need TTS that outputs raw PCM—for example ElevenLabs outputFormat: "pcm_16000" or a Workers AI model with encoding: "linear16" and container: "none". Telnyx is called out as an exception where the browser decodes before playback.
Realtime SFU TTS + STT demo
Section titled “Realtime SFU TTS + STT demo”The AI audio pipelines example (realtime-examples/ai-tts-stt) wires Realtime SFU to browser publisher/player URLs, generates speech from text in the publisher UI, and forwards microphone audio for STT after WebRTC connects. It requires Wrangler secrets (CF_API_TOKEN, REALTIME_SFU_BEARER_TOKEN) and CF_ACCOUNT / REALTIME_SFU_APP_ID in config—useful when speech must be shared between multiple participants, not only processed in a single Worker request.
Common mistakes when wiring speech on Workers
Section titled “Common mistakes when wiring speech on Workers”- Wrong input field — Using
audio_urlon a model that expectsfile, or sending bothurlandfileto Grok STT. - Expecting JSON from aura-1 — Forgetting
returnRawResponse: truewhen the client needs raw audio bytes. - MP3 into telephony — Using default MP3 TTS outputs on Twilio/Plivo without switching to PCM-capable models or formats (Voice).
- WebSocket encoding mismatch — Streaming microphone audio at the wrong sample rate or encoding versus the gateway URL (
linear16/16000for the documented nova-3 example). - Oversized batch audio — Sending entire large files in one Whisper call instead of chunking (Whisper chunking tutorial).
How to check this on your site
Section titled “How to check this on your site”-
From a machine with a valid API token, run the documented
curlfor one STT model (for example AssemblyAI Universal-3 Pro) and confirmstate: "Completed"and non-emptyresult.text. -
Run the matching TTS
curlfor the same provider family (for example Eleven Flash v2.5) and open the returnedresult.audioURL in a browser or player. -
If you use AI Gateway, reproduce the Realtime WebSockets STT snippet with your
account_id,gateway, andcf-aig-authorizationheader; confirm interim and final transcript lines in the console. -
For a full publish/listen loop, deploy the AI audio pipelines example and verify generated speech on the player URL and STT after Start Forwarding on the publisher.
-
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page does not match the linked Cloudflare docs, email yimasynthetic@gmail.com with the page URL and the exact sentence you believe is wrong so it can be corrected or clarified.