TIL: Handling WebSocket Streams With the websockets Library in Python
Python’s websockets library opens a persistent two way connection. It is the cleanest way to stream audio data to a speech-to-text API.
import asyncio
import websockets
async def listen():
async with websockets.connect('wss://api.deepgram.com/v1/listen') as ws:
await ws.send('{type:KeepAlive}')
msg = await ws.recv()
print(msg)
asyncio.run(listen())
The async with block handles connect and disconnect. send and recv are coroutines that look like regular function calls.
async def stream_audio(ws, audio_path):
with open(audio_path, 'rb') as f:
while chunk := f.read(4096):
await ws.send(chunk)
await ws.send('{type:CloseStream}')
Streaming audio works by sending binary chunks through the same WebSocket connection. The API responds with partial transcripts as it processes each chunk.
Does websockets support SSL?
Yes. Use wss:// URLs. The library handles TLS automatically.
What Python version is required?
Python 3.6 or later. The library uses async/await syntax which was stabilised in 3.6.