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

PhaseSDK CallDescription
1. Connectclient.asr.stream()Opens WebSocket, sends StreamingConfig as handshake. Returns a connection object.
2. Streamconn.send_audio()Send raw PCM bytes in chunks. Server emits PARTIAL and FINAL_SEGMENT events continuously.
3. Endconn.end()Signals end of audio. Server emits FINAL event.
4. Closeconn.close()Closes the WebSocket cleanly. Always call after end().

Connection methods

Method / PropertyTypeDescription
send_audio(pcm_bytes)asyncSend a chunk of raw PCM audio bytes.
end()asyncSignal end of audio stream. Triggers FINAL event.
close()asyncClose WebSocket connection cleanly.
is_closedboolWhether the connection is closed.
session_idstringServer-assigned session identifier.