# Real-time transcription

Stream audio over a WebSocket while it is recorded, and get the text back as it is spoken.

`WS /v1/speech-to-text/realtime`

One WebSocket connection is one session. Audio goes in binary frames; everything else is JSON text messages.

The API keeps no transcript of a live session: keep the finals you receive. Its segments can differ from those of a batch transcript of the same audio, which is made from the whole recording at once.

## A session, from start to end

These steps are the [Quickstart](https://platform.vatis.tech/docs/quickstart)'s program, piece by piece: a 16 kHz 16-bit mono WAV file sent as if someone were speaking, with speakers on. The whole program is in [The whole program](https://platform.vatis.tech/docs/realtime#the-whole-program).

## 1. Open the WebSocket

The address is `wss://api.eu.vatis.tech/v1/speech-to-text/realtime`, and only `model_id` is required. Add the session's [options](https://platform.vatis.tech/docs/realtime/query-parameters) to `params`. Open the connection with the header `Authorization: Bearer` and your key; a web page sends a token instead ([Live text in a web page](https://platform.vatis.tech/docs/realtime/live-text-in-a-web-page)).

```javascript
const url = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime";
const headers = { Authorization: `Bearer ${process.env.VATIS_KEY}` };

// Request parameters
const params = { model_id: "vatis_ro_v9_realtime", diarize: "true" };

const ws = new WebSocket(`${url}?${new URLSearchParams(params)}`, { headers });
```

```go
const wsURL = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime"

var headers = http.Header{
	"Authorization": {"Bearer " + os.Getenv("VATIS_KEY")},
}

// Request parameters
var params = url.Values{
	"model_id": {"vatis_ro_v9_realtime"},
	"diarize":  {"true"},
}

// Open the session
ctx := context.Background()
options := &websocket.DialOptions{HTTPHeader: headers}
ws, _, err := websocket.Dial(ctx, wsURL+"?"+params.Encode(), options)
check(err)
```

```python
url = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}

# Request parameters
params = {"model_id": "vatis_ro_v9_realtime", "diarize": "true"}

async with connect(f"{url}?{urlencode(params)}", additional_headers=headers) as ws:
```

```java
static final String url = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime";

// Request parameters
static final String[][] params = {
    {"model_id", "vatis_ro_v9_realtime"},
    {"diarize", "true"},
};

// Open the session: Session prints the messages
// until the server closes the connection
StringJoiner query = new StringJoiner("&");
for (String[] param : params) {
    String value = URLEncoder.encode(param[1], StandardCharsets.UTF_8);
    query.add(param[0] + "=" + value);
}
HttpClient.newHttpClient().newWebSocketBuilder()
    .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
    .buildAsync(URI.create(url + "?" + query), new Session())
    .join();
```

```csharp
var url = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime";
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");

// Request parameters
var parameters = new Dictionary<string, string>
{
    ["model_id"] = "vatis_ro_v9_realtime",
    ["diarize"] = "true",
};

// Open the session
var pairs = parameters.Select(
    (pair) => $"{pair.Key}={Uri.EscapeDataString(pair.Value)}");
var query = string.Join("&", pairs);
using var ws = new ClientWebSocket();
ws.Options.SetRequestHeader("Authorization", $"Bearer {apiKey}");
await ws.ConnectAsync(new Uri($"{url}?{query}"), CancellationToken.None);
```

**Expected result:** the connection opens. JavaScript needs Node.js 22 or later; Go needs Go 1.23 or later and `go get github.com/coder/websocket`; Python needs `pip install --upgrade websockets`; Java needs Java 11 or later and C# .NET 8 or later, with nothing to install.

## 2. Wait for session.started

The first message says the session is ready. Start sending audio when it comes.

```javascript
ws.onmessage = (event) => { // every message, until the server closes the connection
  const message = JSON.parse(event.data);
  if (message.type === "session.started") { // the session is ready: send the audio
    sendAudio();
```

```go
for { // every message, until the server closes the connection
	_, raw, err := ws.Read(ctx)
	if websocket.CloseStatus(err) == websocket.StatusNormalClosure {
		return
	}
	check(err)

	var message Message
	check(json.Unmarshal(raw, &message))
	switch message.Type {
	case "session.started": // the session is ready: send the audio
		go sendAudio(ctx, ws, audio)
```

```python
async for raw in ws:  # every message, until the server closes the connection
    message = json.loads(raw)
    if message["type"] == "session.started":  # the session is ready: send the audio
        asyncio.create_task(send_audio(ws))
```

```java
// onText calls it with every message, until the server closes the connection
void print(WebSocket ws, String raw) {
    switch (field(raw, "type")) {
    case "session.started": // the session is ready: send the audio
        new Thread(() -> sendAudio(ws)).start();
        break;
```

```csharp
var buffer = new byte[65536];
var segment = new ArraySegment<byte>(buffer);
using var received = new MemoryStream(); // a long message comes in parts
while (true) // every message, until the server closes the connection
{
    var part = await ws.ReceiveAsync(segment, CancellationToken.None);
    if (part.MessageType == WebSocketMessageType.Close)
    {
        break;
    }

    received.Write(buffer, 0, part.Count);
    if (!part.EndOfMessage)
    {
        continue;
    }
    var message = JsonDocument.Parse(received.ToArray()).RootElement;
    received.SetLength(0);

    switch (message.GetProperty("type").GetString())
    {
        case "session.started": // the session is ready: send the audio
            _ = SendAudio();
            break;
```

**Expected result:** `session.started`, with every option as the API applied it in `config` (trimmed here). A refused session gets one `error` message instead, then the server closes: [Errors in a session](https://platform.vatis.tech/docs/realtime/errors-in-a-session).

```json
{"type": "session.started", "session_id": "sess_8d41c2a7e09b4f6a9c03d5e1b2a7f480", "model_id": "vatis_ro_v9_realtime",
 "config": {"encoding": "pcm_s16le", "sample_rate": 16000, "commit": "vad", "diarize": true, ...}}
```

## 3. Send audio

Send the audio in binary frames at the pace of real time: 100 ms every 100 ms, which is 3,200 bytes at 16 kHz. The code ends by sending `end`, the last step.

```javascript
async function sendAudio() {
  for (let start = 0; start < audio.length; start += chunkSize) {
    ws.send(audio.subarray(start, start + chunkSize)); // bytes go as a binary frame
    await sleep(100); // at the pace of real time
  }
  ws.send(JSON.stringify({ type: "end" })); // no more audio
}
```

```go
func sendAudio(ctx context.Context, ws *websocket.Conn, audio []byte) {
	for start := 0; start < len(audio); start += chunkSize {
		chunk := audio[start:min(start+chunkSize, len(audio))]
		// bytes go as a binary frame
		check(ws.Write(ctx, websocket.MessageBinary, chunk))
		time.Sleep(100 * time.Millisecond) // at the pace of real time
	}
	// no more audio
	check(ws.Write(ctx, websocket.MessageText, []byte(`{"type": "end"}`)))
}
```

```python
async def send_audio(ws):
    for start in range(0, len(audio), chunk_size):
        await ws.send(audio[start:start + chunk_size])  # bytes go as a binary frame
        await asyncio.sleep(0.1)  # at the pace of real time
    await ws.send(json.dumps({"type": "end"}))  # no more audio
```

```java
static void sendAudio(WebSocket ws) {
    try {
        for (int start = 0; start < audio.length; start += chunkSize) {
            int length = Math.min(chunkSize, audio.length - start);
            ByteBuffer chunk = ByteBuffer.wrap(audio, start, length);
            ws.sendBinary(chunk, true).join(); // bytes go as a binary frame
            Thread.sleep(100); // at the pace of real time
        }
        ws.sendText("{\"type\": \"end\"}", true).join(); // no more audio
    } catch (Exception e) {
        System.out.println(e); // the session ended early
    }
}
```

```csharp
async Task SendAudio()
{
    for (var start = 0; start < audio.Length; start += chunkSize)
    {
        var size = Math.Min(chunkSize, audio.Length - start);
        var chunk = new ArraySegment<byte>(audio, start, size);
        // bytes go as a binary frame
        await ws.SendAsync(
            chunk, WebSocketMessageType.Binary, true, CancellationToken.None);
        await Task.Delay(100); // at the pace of real time
    }
    var end = Encoding.UTF8.GetBytes("""{"type": "end"}"""); // no more audio
    await ws.SendAsync(
        new ArraySegment<byte>(end),
        WebSocketMessageType.Text,
        true,
        CancellationToken.None);
}
```

**Expected result:** no answer to each frame. The text comes as messages, in the next step. The rules for frames: [Sending audio](https://platform.vatis.tech/docs/realtime/sending-audio).

## 4. Read partial and final text

A `partial` is the segment so far, and the next one replaces it. A `final` is a finished segment, and it never changes.

```javascript
} else if (message.type === "partial") { // the words so far, replaced by the next one
  console.log(`... ${message.text}`);
} else if (message.type === "final") { // a finished segment, it never changes
  console.log(`${message.speaker}: ${message.text}`);
} else if (message.type === "session.ended") { // after the last final
  console.log(`done: ${message.duration_s} s of audio`);
} else if (message.type === "error") {
  console.log(`error ${message.code}: ${message.message}`);
}
```

```go
case "partial": // the words so far, replaced by the next one
	fmt.Printf("... %s\n", message.Text)
case "final": // a finished segment, it never changes
	fmt.Printf("%s: %s\n", message.Speaker, message.Text)
case "session.ended": // after the last final
	fmt.Printf("done: %g s of audio\n", message.DurationS)
case "error":
	fmt.Printf("error %s: %s\n", message.Code, message.Message)
}
```

```python
elif message["type"] == "partial":  # the words so far, replaced by the next one
    print(f"... {message['text']}")
elif message["type"] == "final":  # a finished segment, it never changes
    print(f"{message['speaker']}: {message['text']}")
elif message["type"] == "session.ended":  # after the last final
    print(f"done: {message['duration_s']} s of audio")
elif message["type"] == "error":
    print(f"error {message['code']}: {message['message']}")
```

```java
case "partial": // the words so far, replaced by the next one
    System.out.println("... " + field(raw, "text"));
    break;
case "final": // a finished segment, it never changes
    String speaker = field(raw, "speaker");
    System.out.println(speaker + ": " + field(raw, "text"));
    break;
case "session.ended": // after the last final
    System.out.println("done");
    break;
case "error":
    String code = field(raw, "code");
    String reason = field(raw, "message");
    System.out.println("error " + code + ": " + reason);
    break;
default:
}
```

```csharp
    case "partial": // the words so far, replaced by the next one
        Console.WriteLine($"... {message.GetProperty("text")}");
        break;
    case "final": // a finished segment, it never changes
        var speaker = message.GetProperty("speaker");
        Console.WriteLine($"{speaker}: {message.GetProperty("text")}");
        break;
    case "session.ended": // after the last final
        var seconds = message.GetProperty("duration_s");
        Console.WriteLine($"done: {seconds} s of audio");
        break;
    case "error":
        var code = message.GetProperty("code");
        var reason = message.GetProperty("message");
        Console.WriteLine($"error {code}: {reason}");
        break;
}
```

**Expected result:** messages like these. Times are seconds from the start of the session's audio. More on both: [Partial and final text](https://platform.vatis.tech/docs/realtime/partial-and-final-text).

```json
{"type": "partial", "segment_id": 1, "text": "bună ziua", "start": 0.12, "end": 1.28, "speaker": "speaker_0", "words": [...]}
{"type": "partial", "segment_id": 1, "text": "bună ziua luați loc", "start": 0.12, "end": 1.92, "speaker": "speaker_0", "words": [...]}
{"type": "final", "segment_id": 1, "text": "Bună ziua, luați loc.", "start": 0.12, "end": 1.7, "speaker": "speaker_0"}
```

## 5. End the session

When there is no more audio, send `{"type": "end"}`, as the last line of the audio step does, and keep reading until the server closes.

**Expected result:** the last `final` messages, then `session.ended`, then the server closes with code 1000.

```
{"type": "final", "segment_id": 2, "text": "Am venit pe 12 martie.", "start": 3.6, "end": 5.2, "speaker": "speaker_1"}
{"type": "session.ended", "session_id": "sess_8d41c2a7e09b4f6a9c03d5e1b2a7f480", "duration_s": 5.6}
(close 1000)
```

## The whole program

The steps above, as one program: the one the console's Real-time page shows in its Code view. It sends a WAV file at the pace of real time and prints the messages. The file must be 16 kHz, 16-bit, mono: the conversion command is in the program.

```javascript
// Needs Node.js 22 or newer, no packages.
// Set your API key, then run: export VATIS_KEY=your_api_key && node live.mjs
import { readFileSync } from "node:fs";
import { setTimeout as sleep } from "node:timers/promises";

const url = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime";
const headers = { Authorization: `Bearer ${process.env.VATIS_KEY}` };

// Request parameters
const params = {
  model_id: "vatis_ro_v9_realtime",
  diarize: "true",
};

// The audio: a 16 kHz 16-bit mono WAV. To convert a file:
// ffmpeg -i your-audio.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav
const wav = readFileSync("speech.wav");
const audio = wav.subarray(wav.indexOf("data") + 8);
const chunkSize = 3200; // 100 ms of audio

// Open the session
const ws = new WebSocket(`${url}?${new URLSearchParams(params)}`, { headers });

// Send the audio at real-time pace
async function sendAudio() {
  for (let start = 0; start < audio.length; start += chunkSize) {
    ws.send(audio.subarray(start, start + chunkSize));
    await sleep(100);
  }
  ws.send(JSON.stringify({ type: "end" }));
  console.log("finished sending");
}

// Print the messages as they come
ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  if (message.type === "session.started") {
    console.log("connected");
    sendAudio();
  } else if (message.type === "partial") {
    console.log(`... ${message.text}`);
  } else if (message.type === "final") {
    console.log(`${message.speaker}: ${message.text}`);
  } else if (message.type === "session.ended") {
    console.log(`done: ${message.duration_s} s of audio`);
  } else if (message.type === "error") {
    console.log(`error ${message.code}: ${message.message}`);
  }
};

// A failed connection is an error; when the server closes, the program ends
ws.onerror = () => {
  console.error("connection failed");
  process.exit(1);
};
ws.onclose = (event) => {
  if (event.code !== 1000) { // 1000 is the normal end
    console.error(`connection failed: close code ${event.code}`);
    process.exit(1);
  }
  process.exit();
};
```

```go
// Needs Go 1.23 or newer and a WebSocket package. In a new folder:
// go mod init live && go get github.com/coder/websocket, save this as main.go
// Set your API key, then run: export VATIS_KEY=your_api_key && go run .

package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"time"

	"github.com/coder/websocket"
)

const wsURL = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime"
const chunkSize = 3200 // 100 ms of audio

var headers = http.Header{
	"Authorization": {"Bearer " + os.Getenv("VATIS_KEY")},
}

// Request parameters
var params = url.Values{
	"model_id": {"vatis_ro_v9_realtime"},
	"diarize":  {"true"},
}

// Message holds what this code reads of the session's messages.
type Message struct {
	Type      string
	Text      string
	Speaker   string
	DurationS float64 `json:"duration_s"`
	Code      string
	Message   string
}

func main() {
	// The audio: a 16 kHz 16-bit mono WAV. To convert a file:
	// ffmpeg -i your-audio.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav
	wav, err := os.ReadFile("speech.wav")
	check(err)
	audio := wav[bytes.Index(wav, []byte("data"))+8:]

	// Open the session
	ctx := context.Background()
	options := &websocket.DialOptions{HTTPHeader: headers}
	ws, _, err := websocket.Dial(ctx, wsURL+"?"+params.Encode(), options)
	check(err)

	// Print the messages until the server closes the connection
	for {
		_, raw, err := ws.Read(ctx)
		if websocket.CloseStatus(err) == websocket.StatusNormalClosure {
			return
		}
		check(err)

		var message Message
		check(json.Unmarshal(raw, &message))
		switch message.Type {
		case "session.started":
			fmt.Println("connected")
			go sendAudio(ctx, ws, audio)
		case "partial":
			fmt.Printf("... %s\n", message.Text)
		case "final":
			fmt.Printf("%s: %s\n", message.Speaker, message.Text)
		case "session.ended":
			fmt.Printf("done: %g s of audio\n", message.DurationS)
		case "error":
			fmt.Printf("error %s: %s\n", message.Code, message.Message)
		}
	}
}

// sendAudio sends the audio at real-time pace.
func sendAudio(ctx context.Context, ws *websocket.Conn, audio []byte) {
	for start := 0; start < len(audio); start += chunkSize {
		chunk := audio[start:min(start+chunkSize, len(audio))]
		check(ws.Write(ctx, websocket.MessageBinary, chunk))
		time.Sleep(100 * time.Millisecond)
	}
	check(ws.Write(ctx, websocket.MessageText, []byte(`{"type": "end"}`)))
	fmt.Println("finished sending")
}

// check stops the program on an error.
func check(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```python
# Needs Python 3.10 or newer and websockets (pip install --upgrade websockets).
# Set your API key, then run: export VATIS_KEY=your_api_key && python3 live.py
import asyncio
import json
import os
import wave
from urllib.parse import urlencode

from websockets.asyncio.client import connect

url = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}

# Request parameters
params = {
    "model_id": "vatis_ro_v9_realtime",
    "diarize": "true",
}

# The audio: a 16 kHz 16-bit mono WAV. To convert a file:
# ffmpeg -i your-audio.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav
with wave.open("speech.wav") as wav:
    audio = wav.readframes(wav.getnframes())
chunk_size = 3200  # 100 ms of audio

async def send_audio(ws):
    for start in range(0, len(audio), chunk_size):
        await ws.send(audio[start:start + chunk_size])
        await asyncio.sleep(0.1)  # real-time pace
    await ws.send(json.dumps({"type": "end"}))
    print("finished sending")

async def main():
    address = f"{url}?{urlencode(params)}"
    async with connect(address, additional_headers=headers) as ws:
        # Print the messages until the server closes the connection
        async for raw in ws:
            message = json.loads(raw)
            if message["type"] == "session.started":
                print("connected")
                asyncio.create_task(send_audio(ws))
            elif message["type"] == "partial":
                print(f"... {message['text']}")
            elif message["type"] == "final":
                print(f"{message['speaker']}: {message['text']}")
            elif message["type"] == "session.ended":
                print(f"done: {message['duration_s']} s of audio")
            elif message["type"] == "error":
                print(f"error {message['code']}: {message['message']}")

asyncio.run(main())
```

```java
// Needs Java 11 or newer, nothing to install.
// Set your API key, then run: export VATIS_KEY=your_api_key && java Live.java
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.StringJoiner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Live {
    static final String url =
        "wss://api.eu.vatis.tech/v1/speech-to-text/realtime";
    static final int chunkSize = 3200; // 100 ms of audio
    static final CompletableFuture<Void> closed = new CompletableFuture<>();
    static byte[] audio;

    // Request parameters
    static final String[][] params = {
        {"model_id", "vatis_ro_v9_realtime"},
        {"diarize", "true"},
    };

    public static void main(String[] args) throws Exception {
        // The audio: a 16 kHz 16-bit mono WAV. To convert a file:
        // ffmpeg -i your-audio.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav
        byte[] wav = Files.readAllBytes(Path.of("speech.wav"));
        String header = new String(wav, StandardCharsets.ISO_8859_1);
        audio = Arrays.copyOfRange(wav, header.indexOf("data") + 8, wav.length);

        // Open the session: Session prints the messages
        // until the server closes the connection
        StringJoiner query = new StringJoiner("&");
        for (String[] param : params) {
            String value = URLEncoder.encode(param[1], StandardCharsets.UTF_8);
            query.add(param[0] + "=" + value);
        }
        HttpClient.newHttpClient().newWebSocketBuilder()
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .buildAsync(URI.create(url + "?" + query), new Session())
            .join();
        closed.join();
    }

    // Sends the audio at real-time pace.
    static void sendAudio(WebSocket ws) {
        try {
            for (int start = 0; start < audio.length; start += chunkSize) {
                int length = Math.min(chunkSize, audio.length - start);
                ByteBuffer chunk = ByteBuffer.wrap(audio, start, length);
                ws.sendBinary(chunk, true).join();
                Thread.sleep(100);
            }
            ws.sendText("{\"type\": \"end\"}", true).join();
            System.out.println("finished sending");
        } catch (Exception e) {
            System.out.println(e); // the session ended early
        }
    }

    static class Session implements WebSocket.Listener {
        // a long message comes in parts
        final StringBuilder received = new StringBuilder();

        void print(WebSocket ws, String raw) {
            switch (field(raw, "type")) {
            case "session.started":
                System.out.println("connected");
                new Thread(() -> sendAudio(ws)).start();
                break;
            case "partial":
                System.out.println("... " + field(raw, "text"));
                break;
            case "final":
                String speaker = field(raw, "speaker");
                System.out.println(speaker + ": " + field(raw, "text"));
                break;
            case "session.ended":
                System.out.println("done");
                break;
            case "error":
                String code = field(raw, "code");
                String reason = field(raw, "message");
                System.out.println("error " + code + ": " + reason);
                break;
            default:
            }
        }

        @Override
        public CompletionStage<?> onText(WebSocket ws, CharSequence part,
                boolean last) {
            received.append(part);
            if (last) {
                print(ws, received.toString());
                received.setLength(0);
            }
            ws.request(1);
            return null;
        }

        @Override
        public CompletionStage<?> onClose(WebSocket ws, int code,
                String reason) {
            if (code == WebSocket.NORMAL_CLOSURE) {
                closed.complete(null);
            } else {
                String failed = "connection failed: close code " + code;
                closed.completeExceptionally(new RuntimeException(failed));
            }
            return null;
        }

        @Override
        public void onError(WebSocket ws, Throwable error) {
            closed.completeExceptionally(error);
        }
    }

    // Reads a text field of the JSON: Java has no JSON parser built in,
    // a real program would use a library.
    static String field(String json, String name) {
        String value = "\"" + name + "\":\\s*\"((?:[^\"\\\\]++|\\\\.)*+)\"";
        Matcher match = Pattern.compile(value).matcher(json);
        if (!match.find()) {
            return null;
        }
        Pattern escaped = Pattern.compile("\\\\(u....|.)");
        return escaped.matcher(match.group(1)).replaceAll((escape) -> {
            String code = escape.group(1);
            if (code.equals("n")) {
                return "\n";
            }
            if (code.length() > 1) {
                int number = Integer.parseInt(code.substring(1), 16);
                code = String.valueOf((char) number);
            }
            return Matcher.quoteReplacement(code);
        });
    }
}
```

```csharp
// Needs .NET 8 or newer, no packages. In the audio's folder:
// dotnet new console -o live, then put this in live/Program.cs
// Set your API key, then run:
// export VATIS_KEY=your_api_key && dotnet run --project live
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;

var url = "wss://api.eu.vatis.tech/v1/speech-to-text/realtime";
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");

// Request parameters
var parameters = new Dictionary<string, string>
{
    ["model_id"] = "vatis_ro_v9_realtime",
    ["diarize"] = "true",
};

// The audio: a 16 kHz 16-bit mono WAV. To convert a file:
// ffmpeg -i your-audio.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav
var wav = File.ReadAllBytes("speech.wav");
var audio = wav[(wav.AsSpan().IndexOf("data"u8) + 8)..];
const int chunkSize = 3200; // 100 ms of audio

// Open the session
var pairs = parameters.Select(
    (pair) => $"{pair.Key}={Uri.EscapeDataString(pair.Value)}");
var query = string.Join("&", pairs);
using var ws = new ClientWebSocket();
ws.Options.SetRequestHeader("Authorization", $"Bearer {apiKey}");
await ws.ConnectAsync(new Uri($"{url}?{query}"), CancellationToken.None);

// Print the messages until the server closes the connection
var buffer = new byte[65536];
var segment = new ArraySegment<byte>(buffer);
using var received = new MemoryStream(); // a long message comes in parts
while (true)
{
    var part = await ws.ReceiveAsync(segment, CancellationToken.None);
    if (part.MessageType == WebSocketMessageType.Close)
    {
        break;
    }

    received.Write(buffer, 0, part.Count);
    if (!part.EndOfMessage)
    {
        continue;
    }
    var message = JsonDocument.Parse(received.ToArray()).RootElement;
    received.SetLength(0);

    switch (message.GetProperty("type").GetString())
    {
        case "session.started":
            Console.WriteLine("connected");
            _ = SendAudio();
            break;
        case "partial":
            Console.WriteLine($"... {message.GetProperty("text")}");
            break;
        case "final":
            var speaker = message.GetProperty("speaker");
            Console.WriteLine($"{speaker}: {message.GetProperty("text")}");
            break;
        case "session.ended":
            var seconds = message.GetProperty("duration_s");
            Console.WriteLine($"done: {seconds} s of audio");
            break;
        case "error":
            var code = message.GetProperty("code");
            var reason = message.GetProperty("message");
            Console.WriteLine($"error {code}: {reason}");
            break;
    }
}

// 1000 is the normal end, any other close code a failure
if (ws.CloseStatus != WebSocketCloseStatus.NormalClosure)
{
    var closed = (int?)ws.CloseStatus;
    Console.Error.WriteLine($"connection failed: close code {closed}");
    return 1;
}
return 0;

// Sends the audio at real-time pace
async Task SendAudio()
{
    for (var start = 0; start < audio.Length; start += chunkSize)
    {
        var size = Math.Min(chunkSize, audio.Length - start);
        var chunk = new ArraySegment<byte>(audio, start, size);
        await ws.SendAsync(
            chunk, WebSocketMessageType.Binary, true, CancellationToken.None);
        await Task.Delay(100);
    }
    var end = Encoding.UTF8.GetBytes("""{"type": "end"}""");
    await ws.SendAsync(
        new ArraySegment<byte>(end),
        WebSocketMessageType.Text,
        true,
        CancellationToken.None);
    Console.WriteLine("finished sending");
}
```

## In this guide

- [Query parameters](https://platform.vatis.tech/docs/realtime/query-parameters): Every option of a session, set in the query of the WebSocket address.
- [Sending audio](https://platform.vatis.tech/docs/realtime/sending-audio): Raw audio in binary frames at the pace of real time: how much per frame, and the formats a session takes.
- [Messages](https://platform.vatis.tech/docs/realtime/messages): Every JSON message of a session: the ones you send and the ones you receive.
- [Partial and final text](https://platform.vatis.tech/docs/realtime/partial-and-final-text): How a partial grows into a final, what ends a segment, and which text to show and which to store.
- [End of turn](https://platform.vatis.tech/docs/realtime/end-of-turn): For voice bots: end each segment as soon as the caller sounds finished, and know what ended it, to answer sooner.
- [Speakers and channels](https://platform.vatis.tech/docs/realtime/speakers-and-channels): Label each final and each word with its speaker, get the text before its speakers, or transcribe a stereo call with each side labelled.
- [Vocabularies](https://platform.vatis.tech/docs/realtime/vocabularies): Give a live session or a file the names and terms it must get right, and get them written exactly as you listed them.
- [Ending a session](https://platform.vatis.tech/docs/realtime/ending-a-session): End a session without losing the last words, and what the server sends before it closes.
- [Live text in a web page](https://platform.vatis.tech/docs/realtime/live-text-in-a-web-page): Stream from a browser with a single-use token your server makes, so the page never holds your key.
- [Reconnect after a restart](https://platform.vatis.tech/docs/realtime/reconnect-after-a-restart): Connect again after a session ends early, and send the audio from where the transcript is complete.
- [Errors in a session](https://platform.vatis.tech/docs/realtime/errors-in-a-session): How a refused or failed session ends: its error message, its close code, and what to do.

## Next steps

- [Tokens for web pages](https://platform.vatis.tech/docs/authentication#tokens-for-web-pages): every rule of a single-use token.
- [Limits and free credit](https://platform.vatis.tech/docs/limits): how many live sessions your workspace can run at once.
