---
title: "Record browser audio and send it to a speech-to-text API"
description: "Record the microphone with MediaRecorder, turn WebM or Safari MP4 into 16 kHz WAV, and send it to a transcription API through a small server that keeps the key."
url: https://broadrouter.com/blog/record-browser-audio-transcription-api/
lang: en
updated: 2026-11-15
publisher: BroadRouter (a BroadNet site); API by BroadNet Inference, https://inference.broadnet.ai
---

# Record audio in the browser and send it to a speech-to-text API

By the BroadNet Inference team · 6 min read · Published 2026-11-15

Record with getUserMedia and MediaRecorder, picking a format with isTypeSupported, and drop empty chunks. If the API accepts only WAV or MP3, decode the recording in the browser and encode 16 kHz mono WAV, or upload it and convert with ffmpeg on your server. Either way, send it through your own backend so the API key never reaches the browser.

## Key takeaways

-   Browsers record compressed formats: Chrome gives WebM with Opus, and WebKit documents MP4 with AAC for Safari. OpenAI accepts both; APIs that take only WAV or MP3, such as BroadNet, need a conversion step.
-   getUserMedia works only in a secure context (HTTPS or localhost). Elsewhere navigator.mediaDevices is undefined, so check for it before you call it.
-   A 16 kHz mono 16-bit WAV is 32,000 bytes a second. BroadNet's 26,214,400-byte cap fits about 13 minutes 39 seconds of it; split anything longer.
-   decodeAudioData needs the whole file and resamples to its context's rate, so an OfflineAudioContext at 16,000 Hz does the resampling for you.
-   Never call the transcription API from the page. Post the audio to your server, check its size and type there, and add the key in the server.

**On this page**

1.  What format does the browser record?
2.  How do you record from the microphone?
3.  How do you convert the recording to WAV in the browser?
4.  How do you convert on the server instead?
5.  How do you keep the API key out of the browser?
6.  How did we test this?
7.  What does it cost?
8.  Where BroadNet Inference fits

Recording a voice message in a web app takes about thirty lines of JavaScript. The problems start when you send the file: the browser recorded WebM or MP4, the API wants something else, an iPhone returns “Thank you” for a silent clip, and the tutorial you copied puts the API key in the page. This post builds the whole path and tests each piece: record, convert to WAV, check the size and forward through a small server.

The examples target an API that accepts only WAV or MP3. BroadNet Inference is one: its docs list WAV (`audio/wav`) or MP3 (`audio/mpeg`) up to 26,214,400 bytes per file. If your API takes WebM, skip the conversion and keep the rest. OpenAI’s speech-to-text guide lists flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav and webm, up to 25 MB.

## What format does the browser record?

`MediaRecorder` records a compressed format the browser picks, unless you ask for one it supports. Ask with `MediaRecorder.isTypeSupported()` and take the first match:

| Type string | Typical browser |
| --- | --- |
| `audio/webm;codecs=opus` | Chrome, Edge, Firefox |
| `audio/mp4` | Safari ([WebKit documents MP4 with AAC](https://webkit.org/blog/11353/mediarecorder-api/)); Chromium also reported it in our test |
| `audio/ogg;codecs=opus` | Firefox |

In headless Chromium on 2026-11-15, `isTypeSupported` returned true for WebM/Opus and MP4 and false for Ogg/Opus. Treat the table as a starting point, not a promise. MDN notes that `true` means the browser can record the type in principle; recording may still fail if resources run short. Always read `recorder.mimeType` after creating it, and label the upload with that, not with what you asked for.

## How do you record from the microphone?

Two browser rules shape the code. First, `getUserMedia` exists only in a [secure context](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia): HTTPS, `localhost` or a `file:` URL. On plain HTTP from another host, `navigator.mediaDevices` is `undefined`, so calling it throws a `TypeError` rather than asking for permission. Second, the user must grant access, and a refusal raises `NotAllowedError`. Handle both with a message the user can act on.

```js
// record.js: record from the microphone, return a 16 kHz mono WAV Blob.
const TYPES = ["audio/webm;codecs=opus", "audio/mp4", "audio/ogg;codecs=opus"];

export async function startRecording() {
  if (!navigator.mediaDevices?.getUserMedia) {
    throw new Error("Microphone access needs HTTPS (or localhost).");
  }
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  const mimeType = TYPES.find((t) => MediaRecorder.isTypeSupported(t));
  const rec = new MediaRecorder(stream, mimeType ? { mimeType } : {});
  const chunks = [];
  rec.ondataavailable = (e) => { if (e.data.size > 0) chunks.push(e.data); };
  rec.start(1000); // a chunk every second, so a crash loses at most one second
  return () => new Promise((resolve) => {
    rec.onstop = () => {
      stream.getTracks().forEach((t) => t.stop()); // turn the mic indicator off
      resolve(new Blob(chunks, { type: rec.mimeType }));
    };
    rec.stop();
  });
}
```

Three details in it come from real bug reports:

-   **Drop empty chunks.** In an OpenAI forum thread about MediaRecorder on iPhones, one developer found `dataavailable` firing with empty data on iOS, and filtering those chunks fixed it. Another fixed the same symptom by starting with a timeslice, `start(1000)`.
-   **Stop the tracks.** Stopping the recorder does not release the microphone. Without `getTracks().forEach(t => t.stop())` the browser keeps showing the recording indicator.
-   **Don’t time the recording by counting chunks.** MDN warns that timeslice intervals are inexact and can stretch when Safari pauses the microphone or Android Chrome locks the screen. Keep your own timer if you show a duration or enforce a limit.

## How do you convert the recording to WAV in the browser?

The Web Audio API can decode whatever the browser recorded. Two facts from MDN make this short: `decodeAudioData` only works on a complete file, not fragments, so decode after `stop()`; and it resamples the decoded audio to its context’s sample rate. An `OfflineAudioContext` created at 16,000 Hz therefore hands back 16 kHz samples with no extra resampling code. Its constructor accepts any rate from 3,000 to 768,000 Hz.

```js
export async function toWav16k(blob) {
  // decodeAudioData needs the whole file and resamples to the context's rate.
  const ctx = new OfflineAudioContext(1, 1, 16000);
  const audio = await ctx.decodeAudioData(await blob.arrayBuffer());
  return encodeWav(mixDown(audio), 16000);
}

export function mixDown(audio) {
  const out = new Float32Array(audio.length);
  for (let c = 0; c < audio.numberOfChannels; c++) {
    const ch = audio.getChannelData(c);
    for (let i = 0; i < out.length; i++) out[i] += ch[i] / audio.numberOfChannels;
  }
  return out;
}

export function encodeWav(samples, rate) {
  const buf = new ArrayBuffer(44 + samples.length * 2);
  const v = new DataView(buf);
  const str = (o, s) => [...s].forEach((ch, i) => v.setUint8(o + i, ch.charCodeAt(0)));
  str(0, "RIFF"); v.setUint32(4, 36 + samples.length * 2, true); str(8, "WAVE");
  str(12, "fmt "); v.setUint32(16, 16, true); v.setUint16(20, 1, true); // PCM
  v.setUint16(22, 1, true); v.setUint32(24, rate, true);                // mono
  v.setUint32(28, rate * 2, true); v.setUint16(32, 2, true); v.setUint16(34, 16, true);
  str(36, "data"); v.setUint32(40, samples.length * 2, true);
  for (let i = 0; i < samples.length; i++) {
    const s = Math.max(-1, Math.min(1, samples[i]));
    v.setInt16(44 + i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true);
  }
  return new Blob([buf], { type: "audio/wav" });
}
```

Why 16 kHz mono: it is the setting BroadNet’s own ffmpeg example uses (`-ar 16000 -ac 1`), it keeps the speech band, and it is a third of the bytes of 48 kHz. Stereo doubles the size for no gain on a single voice. See [sample rate](https://broadrouter.com/glossary/sample-rate/) for the trade-offs.

The size arithmetic matters, because WAV is uncompressed. 16,000 samples a second at 2 bytes each is 32,000 bytes a second. With the 44-byte header, BroadNet’s 26,214,400-byte cap holds 819 seconds: about 13 minutes 39 seconds. For anything longer, stop the recording at a limit, or split on the server as in [transcribing long audio files](https://broadrouter.com/blog/transcribe-long-audio-files-api/). The [audio splitter](https://broadrouter.com/tools/audio-splitter-ffmpeg/) writes the ffmpeg commands.

Converting in the browser costs the user’s CPU and memory, and the whole decoded clip sits in memory as 32-bit floats. That is fine for voice messages of a few minutes. For long recordings, upload the compressed file and convert on the server instead.

## How do you convert on the server instead?

Send the compressed recording as it is and let ffmpeg do the work. It is less code in the page, a smaller upload, and the same result:

```bash
ffmpeg -i in.webm -ar 16000 -ac 1 out.wav
```

Write the upload to a temporary file rather than piping it into ffmpeg. MP4 files can keep their index at the end, and ffmpeg can’t always read those from a pipe. The [WhatsApp voice-note guide](https://broadrouter.com/guides/transcribe-whatsapp-voice-notes/) uses the same command for `.ogg` files.

## How do you keep the API key out of the browser?

Put a small endpoint between the page and the API. It accepts the recording, converts it if needed, checks the size, adds the key from an environment variable and forwards it. Node 18 and later have `fetch`, `FormData` and `Blob` built in, so this needs no packages:

```js
// server.mjs: POST /transcribe with the recording as the body. The key stays here.
import http from "node:http";
import { execFile } from "node:child_process";
import { mkdtemp, writeFile, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";

const API = process.env.BROADNET_BASE_URL ?? "https://inference.broadnet.ai/v1";
const KEY = process.env.BROADNET_API_KEY;
const FFMPEG = process.env.FFMPEG ?? "ffmpeg";
const MAX = 26_214_400; // BroadNet's per-file cap in bytes
const run = promisify(execFile);

async function readBody(req, limit) {
  const parts = []; let n = 0;
  for await (const c of req) { n += c.length; if (n > limit) throw Object.assign(new Error("too large"), { code: 413 }); parts.push(c); }
  return Buffer.concat(parts);
}

async function toWav(bytes) {
  // Temp files, not pipes: an MP4 from Safari can keep its index at the end.
  const dir = await mkdtemp(join(tmpdir(), "rec-"));
  try {
    await writeFile(join(dir, "in"), bytes);
    await run(FFMPEG, ["-v", "error", "-i", join(dir, "in"), "-ar", "16000", "-ac", "1", join(dir, "out.wav")]);
    return await readFile(join(dir, "out.wav"));
  } finally { await rm(dir, { recursive: true, force: true }); }
}

http.createServer(async (req, res) => {
  const reply = (code, obj) => { res.writeHead(code, { "content-type": "application/json" }); res.end(JSON.stringify(obj)); };
  if (req.method !== "POST" || req.url !== "/transcribe") return reply(404, { error: "not found" });
  try {
    const type = (req.headers["content-type"] ?? "").split(";")[0];
    let body = await readBody(req, 4 * MAX);
    if (type !== "audio/wav" && type !== "audio/mpeg") {
      try { body = await toWav(body); }
      catch { return reply(400, { error: "Could not read the recording." }); }
    }
    if (body.length > MAX) return reply(413, { error: "Recording too long; split it first." });
    const form = new FormData();
    form.append("model", "broadnet/cohere-transcribe-arabic");
    form.append("language", "ar");
    form.append("file", new Blob([body], { type: type === "audio/mpeg" ? "audio/mpeg" : "audio/wav" }),
      type === "audio/mpeg" ? "audio.mp3" : "audio.wav");
    const r = await fetch(`${API}/audio/transcriptions`, {
      method: "POST", headers: { Authorization: `Bearer ${KEY}` }, body: form,
    });
    const data = await r.json();
    return r.ok ? reply(200, { text: data.text }) : reply(r.status, { error: data });
  } catch (e) {
    return reply(e.code === 413 ? 413 : 500, { error: String(e.message ?? e) });
  }
}).listen(process.env.PORT ?? 8787);
```

The page then sends either the WAV or the raw recording:

```js
const stop = await startRecording();
// ...later, when the user taps Stop:
const raw = await stop();
const wav = await toWav16k(raw);          // or send `raw` and let the server convert
const r = await fetch("/transcribe", { method: "POST", headers: { "content-type": wav.type }, body: wav });
const { text } = await r.json();
```

Points worth keeping when you adapt it:

-   **Always send `language`.** BroadNet’s docs say Arabic can otherwise come back transliterated into Latin letters. Use `ar` with the Arabic model, or switch to `broadnet/cohere-transcribe` and the right code for one of its 14 languages.
-   **Return generic errors.** The first version of our test proxy echoed ffmpeg’s error, which included a server file path. The code above returns “Could not read the recording.” instead.
-   **Add authentication and a rate limit** before you deploy it. Otherwise anyone who finds `/transcribe` spends your balance. [LLM API key security](https://broadrouter.com/blog/llm-api-key-security/) covers the rest, and BroadNet keys can be restricted with [IP allow-lists](https://broadrouter.com/guides/api-keys-ip-allow-lists/).
-   **Reject near-silent clips.** Forum reports of invented “Thank you” or “Bye” transcripts involve silent or broken recordings. Check the duration (WAV bytes ÷ 32,000) and, if you can, the signal level before you pay for it.

## How did we test this?

No BroadNet key was used. On 2026-11-15 we ran the code above against a local mock of `/v1/audio/transcriptions`:

1.  **Encoder in Node.** `encodeWav` on one second of a 440 Hz tone with two clipped samples produced 32,044 bytes. Python’s `wave` module read it as 1 channel, 16,000 Hz, 2-byte samples, 16,000 frames, and ffmpeg as `pcm_s16le, 16000 Hz, mono`. The clipped samples came out as 32767 and −32768.
2.  **Browser path in Chromium.** Playwright launched headless Chromium with a fake microphone. `startRecording` recorded 3 seconds as `audio/webm;codecs=opus` (40,563 bytes), and `toWav16k` turned it into a 96,044-byte WAV: 3.0 seconds, 16 kHz, mono.
3.  **Proxy.** The WAV and the raw WebM both returned 200. The mock saw `Bearer` auth, the Arabic model ID, `language=ar` and a 16 kHz mono `audio/wav` file each time; ffmpeg converted the WebM on the server. A 26,214,401-byte WAV got 413 with no upstream call. A body that wasn’t audio got 400.
4.  **Insecure origin.** Loaded from the machine’s LAN address over plain HTTP, the page reported `isSecureContext` false and `startRecording` threw our HTTPS message instead of a `TypeError`.

We did not test Safari or Firefox, or a real transcription. Try a real iPhone before you ship.

## What does it cost?

BroadNet bills transcription per audio minute: $0.0042 for Transcribe Arabic and $0.002 for the multilingual model. An hour of Arabic voice messages is $0.25. Both run on the $5 starting credit, which covers about 1,190 minutes of Arabic. For your own volumes, use the [speech-to-text cost calculator](https://broadrouter.com/tools/speech-to-text-cost-calculator/). The [Arabic speech-to-text buyer’s guide](https://broadrouter.com/blog/arabic-speech-to-text-api-buyers-guide/) compares providers.

## Where BroadNet Inference fits

BroadRouter is BroadNet’s own site. BroadNet Inference transcribes uploaded files: WAV or MP3, one request per file, with a JSON response holding the text. It does not document live or streaming transcription, timestamps or speaker labels. If your app needs words to appear while the user speaks, use a provider with a streaming speech API. For voice messages, notes and forms, where the user records and then sends, the upload flow above is all you need. Setup is in the [Arabic speech-to-text API guide](https://broadrouter.com/guides/arabic-speech-to-text-api/), and the [API reference](https://inference.broadnet.ai/docs?utm_source=broadrouter&utm_medium=referral&utm_campaign=blog-record-browser-audio-transcription-api&utm_content=body) lists the fields. Its privacy statement says audio and transcripts are not retained.

Free tools for this

-   [OpenAI to BroadNet migration helper](https://broadrouter.com/tools/openai-to-broadnet-migration/) Paste OpenAI SDK code; get base URL, key and model edits, a diff and the checks that remain.
-   [max\_tokens calculator for reasoning models](https://broadrouter.com/tools/reasoning-token-budget/) Answer length + reasoning budget + margin = a max\_tokens that does not cut the answer off.
-   [JSON schema generator for LLM structured output](https://broadrouter.com/tools/json-schema-generator/) Sample JSON to strict schema, Pydantic, Zod and a ready request.
-   [LLM JSON output validator](https://broadrouter.com/tools/llm-json-output-validator/) Parse errors by line and column, safe repairs, cut-off detection and JSON Schema checks for model output.

[All free tools](https://broadrouter.com/tools/)

## Terms in this article

[WAV](https://broadrouter.com/glossary/wav/)

WAV (Waveform Audio File Format, or WAVE) is an audio container built on Microsoft and IBM's RIFF format. It usually holds uncompressed linear PCM samples, so its size is predictable: sample rate times bytes per sample times channels, per second.

[Speech-to-text](https://broadrouter.com/glossary/speech-to-text/)

Speech-to-text, also called automatic speech recognition (ASR), is technology that converts spoken audio into written text. A speech-to-text API accepts an audio file or stream and returns a transcript, usually priced per minute of audio. Accuracy is measured with word error rate and varies with accent, dialect and recording quality.

[API key](https://broadrouter.com/glossary/api-key/)

An API key is a secret string that identifies and authorizes a client calling an API. LLM APIs usually expect it in an Authorization: Bearer header, and anyone who holds the key can make requests that are billed to the account that owns it.

[Ogg Opus](https://broadrouter.com/glossary/ogg-opus/)

Ogg Opus is audio encoded with the Opus codec (RFC 6716) and stored in an Ogg container (RFC 7845). It is built for speech and interactive audio at low bitrates, and it is the format WhatsApp uses for voice notes, usually as .ogg or .opus files.

[Sample rate](https://broadrouter.com/glossary/sample-rate/)

Sample rate is the number of audio samples captured per second, measured in hertz (Hz). Speech recognition models commonly expect 16,000 Hz (16 kHz) mono audio. Together with bit depth and channel count, the sample rate sets how large an uncompressed audio file is per minute.

[Streaming](https://broadrouter.com/glossary/streaming/)

Streaming is a way of returning a language model response in small chunks while it is still being generated, instead of as one reply at the end. OpenAI-compatible APIs stream over server-sent events when the request sets stream to true.

[Tool calling](https://broadrouter.com/glossary/tool-calling/)

Tool calling, also called function calling, is an LLM API feature in which the model returns a structured request to run a function the developer has defined, with JSON arguments. The application runs the function and sends the result back; the model never runs code itself.

[Rate limit](https://broadrouter.com/glossary/rate-limit/)

A rate limit is a cap an API places on how much a client can use it in a time window, such as requests per minute or tokens per minute. Requests over the limit are refused, usually with HTTP 429 Too Many Requests, until usage falls back under it.

## Questions

### Can I send a MediaRecorder WebM file straight to a speech-to-text API?

Only if the API accepts WebM. OpenAI's transcription endpoint lists webm and mp4 among its formats. BroadNet accepts WAV and MP3 only, so convert first: in the browser with the Web Audio API, or on your server with ffmpeg -i in.webm -ar 16000 -ac 1 out.wav.

### Why does getUserMedia say navigator.mediaDevices is undefined?

The page is not a secure context. MDN says getUserMedia works only over HTTPS, on localhost or from file URLs. On plain HTTP from another host, navigator.mediaDevices does not exist. Serve the page over HTTPS; localhost is fine for development.

### How long a recording fits in a 25 MB upload as WAV?

16 kHz mono 16-bit WAV is 32,000 bytes a second plus a 44-byte header. BroadNet's cap of 26,214,400 bytes holds about 819 seconds, or 13 minutes 39 seconds. MP3 or a lower sample rate fits more; for longer audio, split it into pieces.

### Why do I get "Thank you" or "Bye" from an empty recording on iPhone?

Developers on OpenAI's forum report short invented phrases from silent or broken recordings, and traced iOS cases to empty dataavailable chunks; filtering chunks with size 0 and starting the recorder with a timeslice fixed it for them. Check the duration before you upload.

### Should the browser call the transcription API directly?

No. Anything in frontend code, including an API key, can be read by the user. Post the audio to your own endpoint, which checks size and type, adds the key from an environment variable, and forwards it.

## Keep reading

-   [Transcribe long audio over 25 MB: split, send and stitch](https://broadrouter.com/blog/transcribe-long-audio-files-api/)
-   [Whisper API alternative: when to switch, and how to test one](https://broadrouter.com/blog/whisper-api-alternative/)
-   [Multilingual speech-to-text API: 14 languages, one endpoint](https://broadrouter.com/blog/multilingual-speech-to-text-api/)
-   [LLM API key security: storage, rotation and IP allow-lists](https://broadrouter.com/blog/llm-api-key-security/)
-   [Arabic speech-to-text API: how to choose one in 2026](https://broadrouter.com/blog/arabic-speech-to-text-api-buyers-guide/)
-   [Voice notes to text for business: WhatsApp and Telegram to tickets](https://broadrouter.com/blog/voice-notes-to-text-for-business/)
-   [A private endpoint starts with a clear workload](https://broadrouter.com/blog/private-endpoint-planning/)
-   [Before fine-tuning: define the problem to solve](https://broadrouter.com/blog/fine-tuning-readiness/)
-   [Guide: Transcribe WhatsApp voice notes to text with an API](https://broadrouter.com/guides/transcribe-whatsapp-voice-notes/)
-   [Guide: Arabic speech-to-text API, step by step](https://broadrouter.com/guides/arabic-speech-to-text-api/)
-   [Guide: Use the OpenAI Node.js SDK with BroadNet Inference](https://broadrouter.com/guides/openai-node-sdk/)

Try it on your real workload. New accounts start with $5 of credit for Gemma and transcription. DeepSeek, GLM and Qwen3.8 need a top-up.

[Get started](https://inference.broadnet.ai/account/?utm_source=broadrouter&utm_medium=referral&utm_campaign=blog-record-browser-audio-transcription-api&utm_content=page-cta) ·

**Sources**

-   [BroadNet Inference API reference: WAV (audio/wav) or MP3 (audio/mpeg) up to 26,214,400 bytes, always send language, JSON response with text (checked 2026-11-15)](https://inference.broadnet.ai/docs?utm_source=broadrouter&utm_medium=referral&utm_campaign=blog-record-browser-audio-transcription-api&utm_content=sources)
-   [MDN, MediaDevices.getUserMedia(): secure contexts only, user permission, NotAllowedError (checked 2026-11-15)](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)
-   [MDN, MediaRecorder.isTypeSupported(): true does not guarantee recording succeeds (checked 2026-11-15)](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/isTypeSupported_static)
-   [MDN, MediaRecorder dataavailable event: timeslice, stop() and inexact intervals (checked 2026-11-15)](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/dataavailable_event)
-   [MDN, BaseAudioContext.decodeAudioData(): resamples to the context rate, complete files only (checked 2026-11-15)](https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/decodeAudioData)
-   [MDN, OfflineAudioContext() constructor: sampleRate from 3,000 to 768,000 Hz (checked 2026-11-15)](https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext/OfflineAudioContext)
-   [WebKit blog, MediaRecorder API: Safari records MP4 with H.264 video and AAC audio, formats detectable at runtime (checked 2026-11-15)](https://webkit.org/blog/11353/mediarecorder-api/)
-   [OpenAI speech to text guide: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav and webm, files up to 25 MB (checked 2026-11-15)](https://developers.openai.com/api/docs/guides/speech-to-text)
-   [OpenAI Developer Community, "MediaRecorder API w/ Whisper not working on mobile browsers", July to December 2024 (checked 2026-11-15)](https://community.openai.com/t/mediarecorder-api-w-whisper-not-working-on-mobile-browsers/866019)
