Moses TTS & STT in JavaScript

Try the APIs with your key, then copy the code: build it yourself. Everything here runs in this browser with @mosesai/tts and @mosesai/stt.

API key

A key with the TTS and STT permissions (console → API keys). It stays in this browser and goes only to moses-ai.com. Use a test key and rotate it afterwards.

Build it yourself

Two packages, no dependencies, for Node.js 18+ and browsers:

npm install @mosesai/tts @mosesai/stt

Realtime or batch?

Where the API key goes:

Realtime TTS: speak an LLM's answer while it is being written

In a browser, play: true plays the audio as it arrives. Open the session in a click or tap: browsers allow sound only after one.

import { MosesTTS } from "@mosesai/tts";

const tts = new MosesTTS({ apiKey: "mk_…" });             // a key limited to your website
const live = await tts.realtime({ voice: "alba", play: true });

for await (const token of llmStream) live.send(token);   // e.g. the deltas of a chat completion
await live.end();                                        // resolves when the whole answer was sent

stopButton.onclick = () => live.cancel();               // barge-in: the voice stops at once
// the same session can speak the next answer; live.close() when you're done

In Node.js you get the audio as PCM (16-bit, mono, 24 kHz) and pass it on, for example to a phone call or a speaker:

import { MosesTTS, pcmToWav } from "@mosesai/tts";
import { writeFile } from "node:fs/promises";

const tts = new MosesTTS({ apiKey: process.env.MOSES_API_KEY });
const live = await tts.realtime({ voice: "german/juergen" }); // warms a worker: the first audio comes fast
const chunks = [];
live.on("segment", (s) => console.log("speaking:", s.text));
live.on("audio", (pcm) => chunks.push(pcm));              // or stream each chunk on right away

await live.speak("Guten Tag! Ihr Termin ist am 3. Dezember um 14:30 Uhr.");
live.close();
await writeFile("answer.wav", Buffer.from(pcmToWav(chunks)));
Batch TTS: a whole text to a WAV file

On your server. speech() returns the finished file; speechStream() passes it on while it's generated.

import { MosesTTS } from "@mosesai/tts";
import { writeFile } from "node:fs/promises";

const tts = new MosesTTS({ apiKey: process.env.MOSES_API_KEY });
const wav = await tts.speech({ input: "Your parcel arrives on Friday.", voice: "alba" });
await writeFile("speech.wav", Buffer.from(wav));

// voices: await tts.voices()  ->  [{ id: "alba", lang: "en", … }, { id: "german/juergen", … }, …]

Serving it to your page (Express), streamed while it's generated:

import express from "express";
import { Readable } from "node:stream";
import { MosesTTS } from "@mosesai/tts";

const tts = new MosesTTS({ apiKey: process.env.MOSES_API_KEY });
const app = express();
app.post("/speech", express.json(), async (req, res) => {
  try {
    const audio = await tts.speechStream({ input: req.body.text, voice: req.body.voice });
    res.type("audio/wav");
    Readable.fromWeb(audio).pipe(res);
  } catch (e) {
    res.status(e.status ?? 500).json({ message: e.message, code: e.code });
  }
});
app.listen(3000);
// in the page: audio.src = URL.createObjectURL(await (await fetch("/speech", { method: "POST", … })).blob())
Realtime STT: live transcription of the microphone

In a browser, listen() asks for the microphone (with echo cancellation) and streams it. Start it in a click or tap.

import { MosesSTT } from "@mosesai/stt";

const stt = new MosesSTT({ apiKey: "mk_…" });             // a key limited to your website
const live = await stt.listen({ language: "en", endpointMs: 500 }); // 500 ms of silence ends a sentence

live.on("speech_started", () => agentVoice.cancel());    // barge-in for voice agents
live.on("partial", (u) => (caption.textContent = u.text)); // while they speak, about every 0.3 s
live.on("final", (u) => console.log(u.id, u.text));       // after each pause
live.on("revision", (u) => console.log("corrected", u.id, u.text)); // replaces the final with that id

stopButton.onclick = async () => console.log(await live.stop()); // the whole transcript

In Node.js, send raw PCM (16-bit, mono, 8–48 kHz) in 20–100 ms chunks, at the pace it's recorded:

import { MosesSTT } from "@mosesai/stt";

const stt = new MosesSTT({ apiKey: process.env.MOSES_API_KEY });
const live = await stt.realtime({ language: "de", sampleRate: 16000 });
live.on("final", (u) => console.log(u.text));

for await (const chunk of pcmStream) live.sendAudio(chunk); // e.g. from a phone call or ffmpeg
console.log(await live.end());                              // the last final, then the transcript
Batch STT: transcribe a recording

On your server. WAV, MP3, FLAC, OGG/Opus, M4A or WebM, up to 25 MB.

import { MosesSTT } from "@mosesai/stt";
import { readFile } from "node:fs/promises";

const stt = new MosesSTT({ apiKey: process.env.MOSES_API_KEY });
const audio = await readFile("call.mp3");

const { text, language, duration } = await stt.transcribe(audio, { filename: "call.mp3" });
const srt = await stt.transcribe(audio, { filename: "call.mp3", format: "srt" }); // or "vtt", "text"
const timed = await stt.transcribe(audio, { filename: "call.mp3", language: "de",
  format: "verbose_json", timestamps: ["word"] });                               // words with start and end

A recording from your page, sent to your server (Express):

import express from "express";
import { MosesSTT } from "@mosesai/stt";

const stt = new MosesSTT({ apiKey: process.env.MOSES_API_KEY });
const app = express();
app.post("/transcribe", express.raw({ type: "*/*", limit: "25mb" }), async (req, res) => {
  try {
    res.json(await stt.transcribe(req.body, { filename: req.query.name ?? "audio.webm" }));
  } catch (e) {
    res.status(e.status ?? 500).json({ message: e.message, code: e.code });
  }
});
app.listen(3000);
// in the page: a MediaRecorder's Blob -> fetch("/transcribe?name=clip.webm", { method: "POST", body: blob })

The endpoint is OpenAI-compatible, so OpenAI's SDKs work too, with the base URL https://moses-ai.com/stt/v1.

Errors are MosesAPIErrors with:

More: the READMEs of @mosesai/tts and @mosesai/stt.

The source of this page

example.js: everything this page does
loading …
example_js.html
loading …