Below is one example of how you might “wire‐up” a Twilio Media Streams call to the Google Cloud Speech-to-Text (STT) real‐time streaming API. In this example the server:
- Exposes a WebSocket endpoint for Twilio’s Media Streams (Twilio will open a WebSocket connection and send JSON “event” messages).
- Processes incoming JSON messages that signal the start of the stream, carry chunks of base64‑encoded audio (“media” events), and finally the stop event.
- Uses a background thread (with a thread‑safe queue) to feed incoming audio data into the Google Cloud Speech streaming recognizer.
- Prints out recognized transcripts in real time.
Note:
• In production you’ll want to add proper error handling, security (for example, TLS and authentication), logging, and (possibly) reconnect logic.
• Make sure that your Twilio TwiML instructs Twilio to connect your call’s media stream to your WebSocket endpoint (using the <Start> verb).
Below is an example using Python’s FastAPI (which supports WebSocket endpoints natively) and the Google Cloud Speech client library.
Example Code
import asyncio
import base64
import json
import threading
import queue
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from google.cloud import speech
app = FastAPI()
# This worker function will read audio chunks from a queue and feed them
# into the Google Cloud Speech streaming recognizer.
def transcribe_worker(audio_queue: queue.Queue):
client = speech.SpeechClient()
# Configure the recognition – update these parameters according to your needs.
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16, # Twilio streams raw audio (PCM linear16)
sample_rate_hertz=8000, # Twilio’s default sample rate for telephony audio; adjust if needed.
language_code="en-US",
)
streaming_config = speech.StreamingRecognitionConfig(
config=config,
interim_results=True,
)
# The generator will yield StreamingRecognizeRequest objects based on items from the queue.
def request_generator():
while True:
audio_chunk = audio_queue.get()
if audio_chunk is None:
break # termination signal received
yield speech.StreamingRecognizeRequest(audio_content=audio_chunk)
# Call the streaming_recognize method and process responses as they arrive.
responses = client.streaming_recognize(config=streaming_config, requests=request_generator())
try:
for response in responses:
for result in response.results:
if result.alternatives:
transcript = result.alternatives[0].transcript
print("Transcript: " + transcript)
except Exception as e:
print(f"Error during transcription: {e}")
@app.websocket("/twilio")
async def twilio_media_stream(websocket: WebSocket):
"""
This WebSocket endpoint receives connection from Twilio Media Streams.
It expects JSON messages that have an 'event' key and, for audio frames, a "media" object containing a base64-encoded "payload".
"""
await websocket.accept()
print("WebSocket connection accepted")
audio_queue = queue.Queue()
# Start a background thread to read audio from the queue and stream it to Google STT.
transcribe_thread = threading.Thread(target=transcribe_worker, args=(audio_queue,))
transcribe_thread.start()
try:
while True:
msg = await websocket.receive_text()
try:
data = json.loads(msg)
except json.JSONDecodeError:
print("Received a non-JSON message")
continue
event = data.get("event")
if event == "start":
# The stream is starting
print("Media stream started")
elif event == "media":
# Process an audio frame.
# (Twilio sends a JSON object similar to:
# { "event": "media",
# "streamSid": "...",
# "media": {
# "payload": "base64-encoded-audio",
# "track": "inbound" }
# } )
media = data.get("media", {})
payload = media.get("payload")
if payload:
# Twilio sends base64 encoded audio; decode it.
audio_data = base64.b64decode(payload)
audio_queue.put(audio_data)
elif event == "stop":
# Signal end of stream.
print("Media stream stopped")
audio_queue.put(None)
break
except WebSocketDisconnect:
print("WebSocket disconnected")
audio_queue.put(None)
# Wait for transcription thread to finish
transcribe_thread.join()
await websocket.close()
print("WebSocket connection closed")
How It Works
-
Twilio TwiML Setup:
In your Twilio Voice TwiML, specify that Twilio should send call media to your WebSocket endpoint. For example:
<Response>
<Start>
<Stream url="wss://your_server_domain/twilio"/>
</Start>
<Say>Welcome. Please speak after the beep.</Say>
</Response>
(Replace wss://your_server_domain/twilio with the actual URL of your deployed WebSocket endpoint.)
-
Handling Incoming WebSocket Messages:
- When Twilio opens the connection, it sends a JSON message with
"event": "start".
- For each media (audio) frame (an event with
"event": "media"), the code decodes the base64‑encoded payload and pushes the raw audio bytes into a thread‑safe queue.
- Finally, when the stream is finished (an event with
"event": "stop"), the code pushes a None value into the queue as a termination signal.
-
Streaming to Google STT:
The background worker thread continuously reads from the queue and generates StreamingRecognizeRequest messages for the Google Cloud Speech API. Transcription responses (including interim results) are printed to the console.
Running the Example
- Make sure you have the Google Cloud Speech library installed:
pip install google-cloud-speech
- Install FastAPI and an ASGI server (for example, Uvicorn):
pip install fastapi uvicorn
- Save the above code (for example, as
main.py), set the GOOGLE_APPLICATION_CREDENTIALS environment variable to point to your Google Cloud service account JSON file, and run:
uvicorn main:app --host 0.0.0.0 --port 8000
- Configure your Twilio Voice application to use the WebSocket URL (for instance,
wss://your-domain:8000/twilio) in the <Stream> directive.
This sample code provides a starting point for real‑time streaming between Twilio media streams and Google STT. In a production environment, you’d likely want to improve error handling, scaling (for handling multiple simultaneous streams), and security (for WebSocket authentication and HTTPS/TLS).