Before you start
- A running Velosyll installation with a recognition model and an active project API key.
- Python 3.11 or later for the shipped SDK, or Node.js 22.17 or later for its built-in WebSocket client.
- A recording you can use. The commands below download an English reading into your working directory.
- Live recognition uses 5 credits per started second of streamed audio (300 per minute). This example streams a prerecorded WAV. To use the file rate, submit the recording as a transcription job. File transcription uses 1 credit per started second (60 per minute).
1. Set the server address and project key
Open a Bash or Zsh shell. Paste the project key when read waits for input. Python users can install the shipped SDK into an active virtual environment. The Node example uses built-in modules.
export VELOSYLL_URL=http://127.0.0.1:8464
read -rs VELOSYLL_API_KEY
export VELOSYLL_API_KEY
printf '\n'curl -fSLo reading.wav "$VELOSYLL_URL/assets/studio-session.wav"curl -fSLo "velosyll-python-0.1.0.zip" "$VELOSYLL_URL/sdk/downloads/velosyll-python-0.1.0.zip"
python -m zipfile -e "velosyll-python-0.1.0.zip" velosyll-wheels
python -m pip install --no-index --find-links=velosyll-wheels -r velosyll-wheels/requirements.txt2. Prepare mono 16 kHz signed 16-bit audio
Python reads a WAV file and strips its container header through the SDK. Node reads headerless little-endian PCM. The FFmpeg command produces both from the same source. On macOS you can also convert the file with afconvert and extract its samples with Python.
ffmpeg -i reading.wav \
-ac 1 -ar 16000 -c:a pcm_s16le live-speech.wav \
-ac 1 -ar 16000 -c:a pcm_s16le -f s16le live-speech.pcmafconvert -f WAVE -d LEI16@16000 -c 1 reading.wav live-speech.wav
python - <<'PY'
from pathlib import Path
import wave
with wave.open("live-speech.wav", "rb") as audio:
Path("live-speech.pcm").write_bytes(audio.readframes(audio.getnframes()))
PY3. Choose a streaming client
The Python SDK handles the opening handshake and finish message. The Node program waits for ready, sends 100 milliseconds of audio per chunk, then sends finish and waits for done. A partial event is the current hypothesis. Use final events when appending segments to your output.
import argparse
import asyncio
import os
import sys
import wave
from velosyll import VelosyllClient, VelosyllError, paced_wav
from websockets.exceptions import WebSocketException
async def transcribe(path, language):
with wave.open(path, "rb") as audio:
if (audio.getnchannels(), audio.getframerate(), audio.getsampwidth()) != (1, 16000, 2):
raise ValueError("Convert the file to mono 16 kHz 16-bit PCM WAV first.")
duration = audio.getnframes() / audio.getframerate()
if not 0 < duration <= 3600:
raise ValueError("Use a nonempty recording no longer than one hour.")
api = VelosyllClient(os.environ["VELOSYLL_API_KEY"],
os.getenv("VELOSYLL_URL", "http://127.0.0.1:8464"))
async with asyncio.timeout(duration + 120):
async for event in api.listen(paced_wav(path), language=language):
if event["type"] in ("partial", "final"):
print(event["type"], event.get("text", ""), flush=True)
elif event["type"] == "done" and event.get("id"):
print("Job ID:", event["id"], flush=True)
return
raise RuntimeError("The stream ended without a saved job ID.")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("wav")
parser.add_argument("language", nargs="?", default="en")
args = parser.parse_args()
try:
asyncio.run(transcribe(args.wav, args.language))
except TimeoutError:
sys.exit("The streaming deadline expired before the recording was saved.")
except (VelosyllError, WebSocketException, OSError, ValueError, KeyError,
wave.Error, RuntimeError) as error:
sys.exit(str(error))import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { setTimeout as sleep } from "node:timers/promises";
const bytesPerSecond = 32_000;
async function sendAudio(socket, file, signal) {
const start = performance.now();
let sent = 0;
for await (const chunk of createReadStream(file, { highWaterMark: 3_200, signal })) {
while (socket.bufferedAmount > 64_000) {
await sleep(20, undefined, { signal });
}
sent += chunk.length;
const due = start + 1000 * sent / bytesPerSecond;
await sleep(Math.max(0, due - performance.now()), undefined, { signal });
socket.send(chunk);
}
socket.send(JSON.stringify({ type: "finish" }));
}
async function main() {
const [file, language = "en"] = process.argv.slice(2);
const key = process.env.VELOSYLL_API_KEY;
if (!file || !key) throw new Error("Set VELOSYLL_API_KEY and supply a raw PCM file.");
const size = (await stat(file)).size;
if (!size || size % 2 || size > bytesPerSecond * 3600) {
throw new Error("Use complete 16-bit samples, up to one hour of audio.");
}
const url = new URL(process.env.VELOSYLL_URL || "http://127.0.0.1:8464");
const loopback = ["127.0.0.1", "[::1]", "localhost"].includes(url.hostname);
if (!(url.protocol === "https:" || (loopback && url.protocol === "http:"))) {
throw new Error("Use HTTPS or a loopback HTTP service.");
}
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
url.pathname = url.pathname.replace(/\/$/, "") + "/v1/listen";
url.search = "";
url.hash = "";
const socket = new WebSocket(url);
const stop = new AbortController();
let timer;
let sending = false;
try {
const id = await new Promise((resolve, reject) => {
timer = setTimeout(() => reject(new Error("Streaming deadline expired.")),
120_000 + Math.ceil(size * 1000 / bytesPerSecond));
socket.addEventListener("open", () => socket.send(JSON.stringify({ key, language })));
socket.addEventListener("error", () => reject(new Error("WebSocket connection failed.")));
socket.addEventListener("close", () => reject(new Error("Socket closed before done.")));
socket.addEventListener("message", ({ data }) => {
try {
const event = JSON.parse(data);
if (event.type === "error") throw new Error(event.message || "Stream rejected.");
if (event.type === "ready" && !sending) {
sending = true;
sendAudio(socket, file, stop.signal).catch(reject);
} else if (event.type === "partial" || event.type === "final") {
console.log(event.type, event.text);
} else if (event.type === "done") {
if (!event.id) throw new Error("Missing saved job ID.");
resolve(event.id);
}
} catch (error) {
reject(error);
}
});
});
console.log("Job ID:", id);
} finally {
clearTimeout(timer);
stop.abort();
socket.close();
}
}
main().catch(error => {
console.error(error.message);
process.exitCode = 1;
});4. Run your client
Use the command for the program you downloaded. The optional final argument is the language of the recording. Each run opens a separate live session and produces its own saved job.
python stream_wav.py live-speech.wav ennode stream-pcm.mjs live-speech.pcm en5. Retrieve the saved transcript
Both programs print the job ID after the server saves the recording. Paste that ID at the prompt. The response contains the current revision and timestamped segments. You can also open the recording in the project Library.
read -r JOB_ID
curl --fail-with-body -sS -H "Authorization: Bearer $VELOSYLL_API_KEY" \
"$VELOSYLL_URL/v1/transcriptions/$JOB_ID/transcript"Expected result
One saved project recording per completed stream, with final text available to other workloads after the socket closes.
Troubleshooting
- Recognition sounds too fast or the initial words are garbled.
- Prepare both inputs at 16 kHz, mono, signed 16-bit little-endian PCM. Give Node the .pcm file and give Python the .wav file. Keep chunk timing at 32,000 bytes per second.
- Another live recording is active.
- Wait for the previous client to receive done, then reopen the stream. The server limits simultaneous capture by identity and across the installation.
- The client receives an error or closes before printing an ID.
- Inspect the reported server message and confirm the project key is active and has available credit. If done includes funding_limit, the available balance or monthly credit quota ended the stream. Check the project Library for the saved recording before replaying the input.