Streaming Audio
Your First Streaming Session
Open a WebSocket session, send audio chunks, and receive live transcripts.
Complete example
python
import asyncio, subprocess
from shunyalabs import AsyncShunyaClient
from shunyalabs.asr import StreamingConfig, StreamingMessageType
async def main():
async with AsyncShunyaClient() as client:
conn = await client.asr.stream(
config=StreamingConfig(language="hi", sample_rate=16000),
)
@conn.on(StreamingMessageType.PARTIAL)
def on_partial(msg):
print(f"[partial] {msg.text}")
@conn.on(StreamingMessageType.FINAL_SEGMENT)
def on_segment(msg):
print(f"[segment] {msg.text}")
@conn.on(StreamingMessageType.FINAL)
def on_final(msg):
print(f"[final] {msg.text}")
# Convert audio to 16kHz mono PCM and stream
pcm = subprocess.run(
["ffmpeg", "-i", "audio.wav", "-ar", "16000",
"-ac", "1", "-f", "s16le", "-"],
capture_output=True,
).stdout
for i in range(0, len(pcm), 4096):
await conn.send_audio(pcm[i : i + 4096])
await conn.end()
await conn.close()
asyncio.run(main())Connection lifecycle
| Phase | SDK Call | Description |
|---|---|---|
| 1. Connect | client.asr.stream() | Opens WebSocket, sends StreamingConfig as handshake. Returns a connection object. |
| 2. Stream | conn.send_audio() | Send raw PCM bytes in chunks. Server emits PARTIAL and FINAL_SEGMENT events continuously. |
| 3. End | conn.end() | Signals end of audio. Server emits FINAL event. |
| 4. Close | conn.close() | Closes the WebSocket cleanly. Always call after end(). |
Connection methods
| Method / Property | Type | Description |
|---|---|---|
send_audio(pcm_bytes) | async | Send a chunk of raw PCM audio bytes. |
end() | async | Signal end of audio stream. Triggers FINAL event. |
close() | async | Close WebSocket connection cleanly. |
is_closed | bool | Whether the connection is closed. |
session_id | string | Server-assigned session identifier. |