Stream a selected enrolled voice
VRVI accepts a workspace-authorized session request, resolves the permitted enrolled human voice named in that request, and returns a short-lived stream token. The long-lived API key is used only for the HTTPS session request.
Authenticate the session request
Send the workspace API key in Authorization: Bearer … or X-VRVI-API-Key over HTTPS. Keep it in your server-side secret store. Do not send it from a browser and never place it in a WebSocket URL.
- The key authorizes the workspace, not a particular human voice.
- Every request must include a permitted
profile_idreturned by the profiles endpoint. - Revoked keys cannot create new sessions.
Enroll once, select by ID per session
Use POST /api/v1/vrvi/profiles with the workspace API key to create a named voice profile. The request is multipart/form-data with a required name and exactly one recording; language_code is optional and defaults to en. Upload a mono 16 kHz 16-bit PCM WAV or raw PCM recording no larger than 10 MB and no longer than 60 seconds.
Use GET /api/v1/vrvi/profiles with the same key to retrieve every active profile as id + name. Store the returned profile ID in your server-side integration and send it as profile_id when creating a session. A workspace has one active API key, but it may have multiple named profiles.
The profile data remains server-side. The API key authorizes the workspace; it does not identify the speaker, and VRVI is not login authentication.
{
"profiles": [
{
"id": "PROFILE_ID",
"name": "Florence guide",
"status": "active",
"language_code": "en",
"created_utc": "UTC_TIMESTAMP",
"updated_utc": "UTC_TIMESTAMP"
}
]
}
Create a session
POST to /api/v1/vrvi/sessions with the selected profile_id and the fixed audio contract. client_session_id is optional and can correlate your own lifecycle records. Keep a request outcome record in your own integration when a network failure leaves session creation uncertain.
The flows below are server-side integrations. Enrollment happens once through the profiles endpoint; store the returned named profile_id with your workspace integration and select it for every session. Each sample keeps the API key on the server, uses the short-lived stream token only for the WebSocket, sends one ordered binary frame at a time, and retains unconfirmed frames for a bounded reconnect.
using System.Buffers.Binary;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Net.WebSockets;
using System.Text.Json.Serialization;
const string dashboardBaseUrl = "https://your-dashboard.example";
const string sessionPath = "/api/v1/vrvi/sessions";
const int sampleRate = 16000;
const int channels = 1;
const int pcmBytes = 640;
const int frameBytes = 648;
string apiKey = Environment.GetEnvironmentVariable("VRVI_API_KEY")
?? throw new InvalidOperationException("VRVI_API_KEY is required.");
Guid profileId = Guid.Parse(Environment.GetEnvironmentVariable("VRVI_PROFILE_ID")
?? throw new InvalidOperationException("Enroll the guide in Dashboard first."));
string clientSessionId = Guid.NewGuid().ToString("N");
await using IAsyncEnumerator<byte[]> audio = ReadPcmFramesAsync(cancellationToken).GetAsyncEnumerator(cancellationToken);
var pending = new Queue<PendingFrame>();
long nextSequence = 1;
int reconnectAttempt = 0;
while (true)
{
try
{
using HttpClient http = new() { BaseAddress = new Uri(dashboardBaseUrl) };
using HttpRequestMessage request = new(HttpMethod.Post, sessionPath)
{
Content = JsonContent.Create(new
{
profile_id = profileId,
sample_rate = sampleRate,
channels,
client_session_id = clientSessionId
})
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
using HttpResponseMessage response = await http.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
VrviSession session = (await response.Content.ReadFromJsonAsync<VrviSession>(cancellationToken))!;
using ClientWebSocket socket = new();
socket.Options.SetRequestHeader("X-VRVI-Stream-Token", session.StreamToken);
await socket.ConnectAsync(new Uri(session.WebSocketUrl), cancellationToken);
while (true)
{
if (pending.Count == 0)
{
if (!await audio.MoveNextAsync())
return;
byte[] pcm = audio.Current;
if (pcm.Length != pcmBytes)
throw new InvalidDataException("The capture source must yield one 20 ms PCM frame.");
pending.Enqueue(new PendingFrame(nextSequence++, pcm));
}
while (pending.Count > 0)
{
PendingFrame current = pending.Peek();
await socket.SendAsync(CreateFrame(current.Sequence, current.Pcm), WebSocketMessageType.Binary, true, cancellationToken);
byte[] output = await ReceiveFrameAsync(socket, cancellationToken);
if (output.Length != frameBytes)
throw new WebSocketException("VRVI returned an invalid response frame.");
long outputSequence = BinaryPrimitives.ReadInt64LittleEndian(output);
if (outputSequence != current.Sequence)
throw new WebSocketException("VRVI returned an unexpected sequence.");
pending.Dequeue(); // the matching binary response confirms this frame
reconnectAttempt = 0;
}
}
}
catch (Exception exception) when (exception is WebSocketException or HttpRequestException)
{
if (++reconnectAttempt > 8)
throw;
await Task.Delay(TimeSpan.FromMilliseconds(Math.Min(4000, 250 * reconnectAttempt)), cancellationToken);
// A closed public socket finalizes its session. Create a new session,
// but keep every pending frame's original sequence number.
}
}
byte[] CreateFrame(long sequence, byte[] pcm)
{
byte[] frame = new byte[frameBytes];
BinaryPrimitives.WriteInt64LittleEndian(frame, sequence);
pcm.CopyTo(frame, sizeof(long));
return frame;
}
async Task<byte[]> ReceiveFrameAsync(ClientWebSocket socket, CancellationToken cancellationToken)
{
byte[] frame = new byte[frameBytes];
int offset = 0;
while (true)
{
ValueWebSocketReceiveResult result = await socket.ReceiveAsync(frame.AsMemory(offset), cancellationToken);
if (result.MessageType == WebSocketMessageType.Close || result.MessageType != WebSocketMessageType.Binary)
throw new WebSocketException("VRVI returned a non-binary response.");
offset += result.Count;
if (result.EndOfMessage)
return frame[..offset];
if (offset == frame.Length)
throw new WebSocketException("VRVI response frame is too large.");
}
}
sealed record PendingFrame(long Sequence, byte[] Pcm);
sealed record VrviSession(
[property: JsonPropertyName("stream_token")] string StreamToken,
[property: JsonPropertyName("websocket_url")] string WebSocketUrl);
// ReadPcmFramesAsync must yield exactly 640 bytes of signed 16-bit mono PCM per item.
import os
import struct
import time
import uuid
from collections import deque
import requests
import websocket
base_url = os.environ["VRVI_BASE_URL"].rstrip("/")
session_url = base_url + "/api/v1/vrvi/sessions"
api_key = os.environ["VRVI_API_KEY"]
profile_id = os.environ["VRVI_PROFILE_ID"] # saved from GET /api/v1/vrvi/profiles
sample_rate = 16000
channels = 1
pcm_bytes = 640
frame_bytes = 648
client_session_id = uuid.uuid4().hex
def create_session():
response = requests.post(
session_url,
headers={"Authorization": f"Bearer {api_key}"},
json={
"profile_id": profile_id,
"sample_rate": sample_rate,
"channels": channels,
"client_session_id": client_session_id,
},
timeout=15,
)
response.raise_for_status()
return response.json()
def make_frame(sequence, pcm):
if len(pcm) != pcm_bytes:
raise ValueError("The capture source must yield one 20 ms PCM frame.")
return struct.pack("<q", sequence) + pcm
def stream():
pending = deque()
audio = iter(read_pcm_frames()) # yields 640 bytes of signed 16-bit mono PCM
next_sequence = 1
reconnect_attempt = 0
while True:
try:
session = create_session()
socket = websocket.create_connection(
session["websocket_url"],
header=[f"X-VRVI-Stream-Token: {session['stream_token']}"],
timeout=15,
)
try:
while True:
if not pending:
pcm = next(audio, None)
if pcm is None:
return
pending.append((next_sequence, pcm))
next_sequence += 1
while pending:
sequence, pcm = pending[0]
socket.send(make_frame(sequence, pcm), opcode=websocket.ABNF.OPCODE_BINARY)
output = socket.recv()
if not isinstance(output, bytes) or len(output) != frame_bytes:
raise websocket.WebSocketException("VRVI returned an invalid binary response.")
if struct.unpack("<q", output[:8])[0] != sequence:
raise websocket.WebSocketException("VRVI returned an unexpected sequence.")
pending.popleft() # matching output confirms this frame
reconnect_attempt = 0
finally:
socket.close()
except (requests.RequestException, websocket.WebSocketException, OSError):
reconnect_attempt += 1
if reconnect_attempt > 8:
raise
time.sleep(min(4.0, 0.25 * reconnect_attempt))
# A closed public socket finalizes its session. Create a new session,
# but keep pending frames and their original sequence numbers.
stream()
import { randomUUID } from "node:crypto";
import WebSocket from "ws";
const dashboardBaseUrl = process.env.VRVI_BASE_URL ?? "https://your-dashboard.example";
const sessionPath = "/api/v1/vrvi/sessions";
const apiKey = process.env.VRVI_API_KEY;
const profileId = process.env.VRVI_PROFILE_ID; // saved from GET /api/v1/vrvi/profiles
const sampleRate = 16000;
const channels = 1;
const pcmBytes = 640;
const frameBytes = 648;
const clientSessionId = randomUUID();
if (!apiKey || !profileId) throw new Error("Configure VRVI_API_KEY and VRVI_PROFILE_ID.");
async function createSession() {
const response = await fetch(new URL(sessionPath, dashboardBaseUrl), {
method: "POST",
headers: {
"Authorization": "Bearer " + apiKey,
"Content-Type": "application/json"
},
body: JSON.stringify({
profile_id: profileId,
sample_rate: sampleRate,
channels,
client_session_id: clientSessionId
})
});
if (!response.ok) throw new Error("VRVI session failed: " + response.status);
return await response.json();
}
function createFrame(sequence, pcm) {
if (pcm.length !== pcmBytes) throw new Error("Expected one 20 ms PCM frame.");
const frame = Buffer.alloc(frameBytes);
frame.writeBigInt64LE(BigInt(sequence), 0);
Buffer.from(pcm).copy(frame, 8);
return frame;
}
function connect(session) {
return new Promise((resolve, reject) => {
const socket = new WebSocket(session.websocket_url, {
headers: { "X-VRVI-Stream-Token": session.stream_token }
});
socket.once("open", () => resolve(socket));
socket.once("error", reject);
});
}
function sendAndReceive(socket, frame, expectedSequence) {
return new Promise((resolve, reject) => {
const fail = error => {
cleanup();
reject(error);
};
const onMessage = (data, isBinary) => {
if (!isBinary) return fail(new Error("VRVI returned a non-binary response."));
const output = Buffer.from(data);
if (output.length !== frameBytes || output.readBigInt64LE(0) !== BigInt(expectedSequence))
return fail(new Error("VRVI returned an unexpected sequence."));
cleanup();
resolve(output);
};
const onClose = () => fail(new Error("VRVI socket closed before the frame was confirmed."));
const cleanup = () => {
socket.removeListener("message", onMessage);
socket.removeListener("close", onClose);
socket.removeListener("error", fail);
};
socket.on("message", onMessage);
socket.once("close", onClose);
socket.once("error", fail);
socket.send(frame, error => { if (error) fail(error); });
});
}
async function stream() {
const pending = [];
const audio = readPcmFrames()[Symbol.asyncIterator](); // yields 640-byte PCM frames
let nextSequence = 1;
let reconnectAttempt = 0;
while (true) {
let socket;
try {
const session = await createSession();
socket = await connect(session); // one WebSocket for this session
while (true) {
if (pending.length === 0) {
const next = await audio.next();
if (next.done) return;
const pcm = Buffer.from(next.value);
if (pcm.length !== pcmBytes) throw new Error("Expected one 20 ms PCM frame.");
pending.push({ sequence: nextSequence++, pcm });
}
while (pending.length > 0) {
const current = pending[0];
await sendAndReceive(socket, createFrame(current.sequence, current.pcm), current.sequence);
pending.shift(); // matching output confirms this frame
reconnectAttempt = 0;
}
}
} catch (error) {
if (++reconnectAttempt > 8) throw error;
await new Promise(resolve => setTimeout(resolve, Math.min(4000, 250 * reconnectAttempt)));
// Create a new HTTPS session after a close; never reset pending sequence numbers.
} finally {
socket?.close();
}
}
}
await stream();
Use the short-lived stream token
The session response contains stream_token, stream_id, websocket_url, and expires_utc. Use the short-lived token only to open the returned WebSocket. Native clients should send X-VRVI-Stream-Token; browser clients may append it as the token query parameter because browser WebSocket APIs cannot set a custom header. Never put the long-lived API key in the WebSocket URL.
Connect one WebSocket per session
Connect to the returned URL before the token expires and keep exactly one socket for that created session. Send complete binary frames only. The public stream endpoint is /api/v1/vrvi/streams; the returned URL may include the deployment host and path.
using var socket = new ClientWebSocket();
socket.Options.SetRequestHeader("X-VRVI-Stream-Token", session.StreamToken);
await socket.ConnectAsync(new Uri(session.WebSocketUrl), cancellationToken);
Send ordered audio frames
Each binary frame is exactly 648 bytes: a positive little-endian 64-bit sequence number followed by 640 bytes of signed 16-bit little-endian mono PCM at 16000 Hz. The PCM portion represents one 20 ms frame. The service returns a binary output frame with the same sequence number after processing. Do not trim, merge, reorder, skip, or replay an acknowledged frame.
Reconnect without changing ordering
A closed public socket finalizes its created stream. On transport failure, use bounded backoff, create a new HTTPS session, and open one new WebSocket for that session. Keep the locally unconfirmed frame at the head of your queue and resend it with its original sequence number; remove a frame only after the matching binary response is received. Never reset the queue sequence or open concurrent sockets for one session.
Handle HTTP errors and WebSocket closes
400means the request or audio contract is invalid.401means the API key or stream token is invalid, expired, or missing.403means the voice subject is not permitted for the workspace.409means the selected voice is not enrolled or the stream state conflicts.429means a service or account rate limit was reached.502or503means the VRVI service is unavailable; retry with bounded backoff.
WebSocket close codes are lifecycle signals. Treat an unexpected close as a reconnect decision, not permission to create an unbounded set of sockets.
Keep the client bounded
Use the returned sample rate, channel count, frame size, and expiry values. Bound in-flight writes, queue memory, reconnect attempts, and request deadlines. A socket that is open but carries no accepted audio does not create billable usage.
Billing follows accepted audio
External VRVI usage is recorded against the API-key workspace from accepted audio checkpoints and the existing Dashboard usage ledger. Monthly marginal tiers are $0.90/hour for the first 500 hours, $0.60/hour for hours 500–5,000, and $0.45/hour above 5,000. Internal TourVoice usage is non-billable.
Revoke at the workspace boundary
Revoke a key from the Dashboard when a server, integration, or operator no longer needs it. Revocation blocks new HTTPS session creation. It does not retroactively erase usage or terminate a stream that has already been issued; let that short-lived stream expire or close it in your client.
Keep credentials and profiles server-side
- Store API keys in a server-side secret manager and rotate them when access changes.
- Use HTTPS for every session request and never log API keys or stream tokens.
- Keep voice subject IDs scoped to your authorized workspace records.
- Use a short request deadline, cancellation, and bounded retries around session creation.