Skip to main content
Stream a WAV file and print transcripts.
import asyncio
import json
import websockets

API_KEY = "YOUR_API_KEY"
AUDIO_FILE = "audio.wav"

async def transcribe():
    url = (
        "wss://api.telnyx.com/v2/speech-to-text/transcription"
        "?transcription_engine=Deepgram"
        "&model=nova-3"
        "&input_format=wav"
        "&interim_results=true"
    )
    headers = {"Authorization": f"Bearer {API_KEY}"}

    async with websockets.connect(url, extra_headers=headers) as ws:
        async def listen():
            async for message in ws:
                data = json.loads(message)
                prefix = "FINAL" if data.get("is_final") else "partial"
                print(f"[{prefix}] {data.get('transcript', '')}")

        listener = asyncio.create_task(listen())

        with open(AUDIO_FILE, "rb") as f:
            while chunk := f.read(4096):
                await ws.send(chunk)
                await asyncio.sleep(0.05)

        await asyncio.sleep(3)
        await ws.send(json.dumps({"type": "CloseStream"}))
        listener.cancel()

asyncio.run(transcribe())