Skip to main content
Stream a short reply to Coda token by token and save the audio to output.pcm. You can run it without an audio device, then convert the file to WAV to hear it.

Prepare the client

Install uv and Python 3.11 or later. Create a Rime API key, then set RIME_API_KEY in your server’s environment. Keep the key out of browser code and source control. Create a project and install the WebSocket client:

Stream audio to a file

Save this as stream_json.py. It connects to wss://coda.api.rime.ai/ws with rime.v1.json and overwrites output.pcm in the current directory. The sender and receiver run together so audio can arrive while the client sends more text. For Protobuf messages, use the Protobuf quickstart.
The script has four functions:
  • send_tokens: sends each token as a text message, then sends end. Because start sets SPLIT_STRATEGY_ACCUMULATE_SENTENCE, the server joins the tokens into sentences. To stream input over time, replace TOKENS with your model’s output.
  • receive_audio: reads events for turn-1 until done, and writes each audio chunk. To route audio to a browser, phone system, or player, replace the await write_audio(...) call with your audio handler.
  • write_audio: writes each chunk on a worker thread. The receiver waits for each write before it reads the next message, so chunks stay in order. On cancellation, it waits for the active write before it closes the file.
  • main: connects, waits for ready, sends start, and runs the sender and receiver together. It closes the connection after done. In a persistent application, keep the socket open, start each turn with a new contextId, and dispatch every turn’s events from one receive loop. See lifecycle and interruption handling.
Run the script after setting your API key:
A successful run prints a request ID and Saved output.pcm. The file contains raw mono, signed 16-bit little-endian PCM at 24 kHz, with no WAV header, and a failed run can leave a partial file. To hear the audio, convert it to WAV.

Listen to the result

Most players do not open headerless PCM. This command wraps output.pcm in a WAV header and saves output.wav, which any audio player opens:

Use another language or audio format

Set language and speaker together for the desired voice. Set the audio MIME type in audioParameters.audioFormat. Every JSON audio payload is base64 regardless of the selected audio format. Decode it once, then send the bytes to the right player or decoder. For live playback of MP3, Opus, or WAV, use a streaming decoder for that format, and keep it open for the whole context. See audio parameters for sample rates and byte formats.