# Speech

Turn speech into text from a recording or live while a person speaks, relay a browser's microphone through your backend, and read text aloud, with what each one costs.

Source: https://docs.omazy.ai/build-on-omazy/speech/

import { Tabs, TabItem } from '@astrojs/starlight/components'

Three things, all under the `voice:speech` scope:

| You have | Use | Text arrives |
|---|---|---|
| A finished recording | `voice.transcribe` | About 4 s after upload for a 5 s clip |
| A person speaking now | `voice.transcribeStream` | About 0.3 s after they stop |
| Text to read aloud | `voice.speak` | WAV audio |

Speech is counted in voice minutes, the plan's unit for anything spoken or
heard. Each request, or each live session, rounds up to whole minutes with a
minimum of one. That minimum shapes the calls below.

## Transcribe a recording

```ts
const clip = await readFile('question.webm')
const { text, language } = await omazy.voice.transcribe(clip, {
  lang: 'en',
  terms: ['Rashed Karim', 'Nordwell'],
})
console.log(language, text)
```

`terms` are the names and words you expect: staff names, your brand, product
names. Without them "Rashed Karim" can come back as "Rasht Kareem". With them
it comes back right, in English and in Bangla. At most 200 terms of at most
100 bytes each. More is refused with `400`, never cut short, so a list that
grows with your customer's staff needs a check before it is sent.

The audio is WebM, Ogg or WAV, at most 8 MB. The format is read from the
audio. `lang` is `en` or `bn`, the language to expect first.

<Tabs syncKey="sdk-lang">
<TabItem label="TypeScript">

```ts
const { text, language } = await omazy.voice.transcribe(clip, { lang: 'en', terms: ['Rashed Karim', 'Nordwell'] })
```

</TabItem>
<TabItem label="Python">

```python
with open("question.webm", "rb") as f:
    heard = omazy.voice.transcribe(f.read(), lang="en", terms=["Rashed Karim", "Nordwell"])
print(heard["language"], heard["text"])
```

</TabItem>
<TabItem label="Go">

```go
// The terms are the trailing arguments.
text, language, err := c.Voice.Transcribe(ctx, clip, "en", "", "Rashed Karim", "Nordwell")
```

</TabItem>
</Tabs>

## Transcribe live audio

A finished recording is heard after it ends. A live session hears the person
while they speak, so the text is ready a few hundred milliseconds after they
stop. Measured on production, 0.27 to 0.45 s after the last audio: the same
as calling the speech vendor directly.

```ts
declare const microphone: AsyncIterable<Uint8Array> // 16 kHz, 16-bit, mono PCM

const session = await omazy.voice.transcribeStream({
  language: 'en',
  terms: ['Rashed Karim'],
  audioFormat: 'pcm_s16le',
  sampleRate: 16000,
  onEvent: (e) => {
    if (e.type === 'partial') process.stdout.write(`\r${e.text}`)
  },
})
for await (const chunk of microphone) session.send(chunk)
const done = await session.end()
console.log(done.text, done.audio_ms)
```

The session is a WebSocket from your server to Omazy, with your token on the
upgrade. What you send and receive:

| You | Omazy |
|---|---|
| Open with `language`, `terms` and the audio format | `ready` when the recognizer is up |
| `send(chunk)` as audio is captured, 20 to 100 ms per chunk | `partial`: the words so far. Show them, do not keep them |
| `commit()` when the person stops, for example when they let go of the button | `final` with `committed: true`, even when nothing was said |
| `keepalive()` while nobody speaks | |
| `end()` when you are done | `done`: every final joined, and `audio_ms`, the length it is billed by |

`commit()` and `end()` wait 30 seconds for their answer, then fail with
`STREAM_ERROR`. Change it per call: `{ timeoutMs: 10_000 }` in TypeScript,
`timeout=10` in Python. In Go the context's deadline is the limit, so give
`Commit` and `End` a context with one.

Audio sent before `ready` is kept and heard in order. Do not wait for it:
the socket takes about a second to come up, and that second should be hidden
behind the person's first words.

The formats: `auto` (the default) for a WebM/Opus, Ogg or WAV stream, or raw
`pcm_s16le`, `mulaw` or `alaw` with a `sampleRate` from 8000 to 48000.

<Tabs syncKey="sdk-lang">
<TabItem label="TypeScript">

```ts
const session = await omazy.voice.transcribeStream({
  language: 'en',
  terms: ['Rashed Karim'],
  audioFormat: 'pcm_s16le',
  sampleRate: 16000,
})
for await (const chunk of microphone) session.send(chunk)
const done = await session.end()
```

</TabItem>
<TabItem label="Python">

```python
with omazy.voice.transcribe_stream(
    language="en", terms=["Rashed Karim"], audio_format="pcm_s16le", sample_rate=16000
) as session:
    for chunk in mic:
        session.send(chunk)
    done = session.end()
    print(done["text"], done["audio_ms"])
```

</TabItem>
<TabItem label="Go">

```go
s, err := c.Voice.TranscribeStream(ctx, omazy.TranscribeStreamOptions{
	Language: "en", Terms: []string{"Rashed Karim"}, AudioFormat: "pcm_s16le", SampleRate: 16000,
})
if err != nil {
	return err
}
defer s.Close()
for chunk := range mic {
	if err := s.Send(chunk); err != nil {
		return err
	}
}
done, err := s.End(ctx)
```

</TabItem>
</Tabs>

### One stream per visit, a commit per press

A session is billed once, when it closes: its audio rounded up to whole
minutes, with a minimum of one. Ten presses of a talk button as ten sessions
cost ten minutes. The same ten presses in one session cost what was said,
often one minute.

So hold one session for the whole visit or conversation:

- **Open** it when the visit starts, or at the first press.
- **Commit** each time the person lets go. The answer to that press is every
  `final` since the previous commit, joined: a pause in the middle of a
  sentence ends a `final` of its own before you commit.
- **Keep it alive.** Omazy closes a session that sends nothing for 60 seconds.
  Send `keepalive()` every 20 to 30 seconds while nobody speaks.
- **End** it when the visit ends. A session also ends on its own after 30
  minutes.

## Relay from a browser

A browser cannot hold your token, so it cannot open the session itself. It
streams to your backend, and your backend relays to Omazy. This Worker is the
relay a production kiosk product runs, cut down to its parts: one session per
browser connection, audio forwarded as it comes, a commit per press, and
keepalives during silence.

```ts
import { Omazy, OmazyError, type TranscriptionSession } from '@omazyai/sdk'

interface Env {
  OMAZY_CORE_TOKEN: string
}

const TERMS = ['Rashed Karim', 'Nordwell']

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    if (new URL(request.url).pathname !== '/speech') return new Response('Not found', { status: 404 })
    if (request.headers.get('upgrade') !== 'websocket') return new Response('Expected a WebSocket', { status: 426 })

    // Check here that the browser belongs to a signed-in user of yours.

    const [client, browser] = Object.values(new WebSocketPair())
    browser.accept()

    const omazy = new Omazy({ token: env.OMAZY_CORE_TOKEN })
    let heard: string[] = [] // finals since the last press
    let session: TranscriptionSession | undefined
    const early: ArrayBuffer[] = [] // audio that arrives while the session opens
    let lastAudio = Date.now()

    // One session for the whole visit. It opens while the person starts
    // speaking, so the dial time is hidden behind their first words.
    const opening = omazy.voice
      .transcribeStream({
        language: 'en',
        terms: TERMS,
        audioFormat: 'pcm_s16le',
        sampleRate: 16000,
        onEvent: (e) => {
          if (e.type === 'partial') browser.send(JSON.stringify({ type: 'partial', text: e.text }))
          if (e.type === 'final' && !e.committed && e.text) heard.push(e.text)
        },
      })
      .then((s) => {
        session = s
        for (const chunk of early.splice(0)) s.send(chunk)
        return s
      })

    opening.catch((err) => {
      const code = err instanceof OmazyError ? err.code : 'UNKNOWN'
      browser.send(JSON.stringify({ type: 'error', code }))
      browser.close(1011, 'speech unavailable')
    })

    // Omazy closes a session that sends nothing for 60 seconds.
    const keepalive = setInterval(() => {
      if (session && Date.now() - lastAudio > 20_000) session.keepalive()
    }, 10_000)

    browser.addEventListener('message', async (ev) => {
      if (typeof ev.data !== 'string') {
        lastAudio = Date.now()
        if (session) session.send(ev.data)
        else early.push(ev.data)
        return
      }
      const msg = JSON.parse(ev.data) as { type: string }
      if (msg.type === 'commit') {
        // The button was let go: the answer is every final since the last press.
        try {
          const last = await (await opening).commit()
          const text = [...heard, last.text].join(' ').trim()
          heard = []
          browser.send(JSON.stringify({ type: 'final', text }))
        } catch (err) {
          // Fall back to POST /voice/transcribe with the recorded clip, if you kept it.
          browser.send(JSON.stringify({ type: 'error', code: err instanceof OmazyError ? err.code : 'UNKNOWN' }))
        }
      }
    })

    browser.addEventListener('close', async () => {
      clearInterval(keepalive)
      try {
        const done = await (await opening).end()
        console.log(JSON.stringify({ evt: 'stt_session', audio_ms: done.audio_ms, request_id: done.request_id }))
      } catch {
        session?.close()
      }
    })

    return new Response(null, { status: 101, webSocket: client })
  },
} satisfies ExportedHandler<Env>
```

The page side captures 16 kHz mono PCM and sends it while the button is down.
A small AudioWorklet turns the microphone's samples into 16-bit integers:

```js
// /pcm-worklet.js: turns the microphone's float samples into 16-bit PCM.
class Pcm extends AudioWorkletProcessor {
  process(inputs) {
    const channel = inputs[0][0]
    if (channel) {
      const out = new Int16Array(channel.length)
      for (let i = 0; i < channel.length; i++) {
        const s = Math.max(-1, Math.min(1, channel[i]))
        out[i] = s < 0 ? s * 0x8000 : s * 0x7fff
      }
      this.port.postMessage(out.buffer, [out.buffer])
    }
    return true
  }
}
registerProcessor('pcm', Pcm)
```

The page, as a module script:

```ts
// In the browser. The page talks to your backend, never to Omazy.
const socket = new WebSocket('wss://your-product.example/speech')
socket.binaryType = 'arraybuffer'

socket.onmessage = (ev) => {
  const msg = JSON.parse(ev.data as string) as { type: string; text?: string; code?: string }
  if (msg.type === 'partial') showDraft(msg.text ?? '')
  if (msg.type === 'final') submit(msg.text ?? '')
  if (msg.type === 'error') showError(msg.code ?? 'UNKNOWN')
}

// 16 kHz mono PCM from the microphone, through an AudioWorklet.
const audio = new AudioContext({ sampleRate: 16000 })
await audio.audioWorklet.addModule('/pcm-worklet.js')
const mic = audio.createMediaStreamSource(await navigator.mediaDevices.getUserMedia({ audio: true }))
const pcm = new AudioWorkletNode(audio, 'pcm')
mic.connect(pcm)

let talking = false
let pending: Int16Array[] = []
let samples = 0

pcm.port.onmessage = (ev: MessageEvent<ArrayBuffer>) => {
  if (!talking) return
  const chunk = new Int16Array(ev.data)
  pending.push(chunk)
  samples += chunk.length
  // Send about 40 ms at a time.
  if (samples >= 640) flush()
}

function flush() {
  if (!samples) return
  const frame = new Int16Array(samples)
  let at = 0
  for (const c of pending) {
    frame.set(c, at)
    at += c.length
  }
  pending = []
  samples = 0
  socket.send(frame.buffer)
}

const button = document.querySelector<HTMLButtonElement>('#talk')!
button.onpointerdown = () => {
  talking = true
}
button.onpointerup = () => {
  talking = false
  flush()
  socket.send(JSON.stringify({ type: 'commit' }))
}

declare function showDraft(text: string): void
declare function submit(text: string): void
declare function showError(code: string): void
```

When the session fails, the relay sends an `error` with the code. A product
that keeps the recording of each press can then send it to
`voice.transcribe` instead, which is slower but independent of the live
session. The codes are on
[Transcribe live audio](/reference/core-api/speech-and-calls/#transcribe-live-audio).

## Read text aloud

```ts
const spoken = await omazy.voice.speak('Your order has shipped and arrives on Thursday.')
await writeFile('reply.wav', new Uint8Array(spoken.audio))
console.log(spoken.language)
```

The text is read in the app's own voice, as set in the console under Voice.
Markdown and links are cleaned out first, so an answer can go in as it was
written. At most 2000 characters. The audio is WAV, 16-bit PCM, mono,
24000 Hz.

Each request is at least one voice minute. Send a whole reply at a time, not
one sentence per request.

<Tabs syncKey="sdk-lang">
<TabItem label="TypeScript">

```ts
const { audio, language } = await omazy.voice.speak('Your order has shipped and arrives on Thursday.')
```

</TabItem>
<TabItem label="Python">

```python
wav, spoken = omazy.voice.speak("Your order has shipped and arrives on Thursday.")
```

</TabItem>
<TabItem label="Go">

```go
wav, spoken, err := c.Voice.Speak(ctx, "Your order has shipped and arrives on Thursday.", "", "")
```

</TabItem>
</Tabs>

`voice.speak` answers once the whole clip is made. It does not stream audio
yet, so a product that must start speaking within a second of the answer
should split a long reply at sentence ends and accept the cost of the extra
requests, or keep replies short.

## Reference

- [Speech and calls](/reference/core-api/speech-and-calls/): every frame, field and error
- [Your plan's voice minutes](/reference/core-api/errors-and-limits/#your-plans-voice-minutes)
