Someone sends a 40-second voice note. The recipient is on a train, in a meeting, or doesn’t want to listen to 40 seconds of anything. So the note sits there, unplayed, for six hours.
Every app that ships voice messages eventually ships transcription, and for the same reason: a voice note is faster to send and slower to receive, and that asymmetry is where the feature dies. WhatsApp added it. Telegram added it. Apple added it. If your product has a mic button, this is on your roadmap whether it’s written down or not.
It’s a small build. Voice notes are the classic short-clip job: a few seconds to a few minutes, one speaker, already recorded by the time you see them. That’s the shape the Sync API is built for. You POST the audio and get the finished transcript back in the same response, with no job IDs, no polling, and no queue.
This tutorial builds the feature end to end in Python (with JavaScript versions of the core calls), then handles the backlog of notes your users have already sent. All of the code is in the companion repo: github.com/kelsey-aai/voice-note-transcription-sync-api.
What you’ll build
- Receive an uploaded voice note on your server and check it
- Transcribe it in a single call
- Render the text inline, under the waveform
- Handle multilingual inboxes
- Backfill the notes already sitting in your database
- Route long notes to the right endpoint
Prerequisites: an AssemblyAI API key, Python 3.8+ (Node.js 18+ for the JavaScript examples), and ffmpeg.
Step 1: Receive the note and check it before you send it
The Sync API has two endpoints with different limits, and which one you call decides whether you need to convert the audio first:
POST /v1/transcribe | POST /v1/transcribe/live | |
|---|---|---|
| Who calls it | Your code, over HTTP | The Python and JavaScript SDKs (every transcribe() call), or HTTP |
| Duration | 80 ms to 20 minutes | Up to 120 seconds |
| File size | Up to 256 MB | Up to 256 MB |
| Formats | WAV, raw PCM, AAC, MP3, M4A, Ogg/Opus, FLAC, WebM | WAV or raw PCM (16-bit) |
| Over the limit | 413 Audio Too Large before transcription | 413 Audio Too Large mid-upload |
Most mobile clients record AAC in an m4a container or Opus in WebM. The HTTP endpoint takes those files as they are. The SDKs send every request through the live endpoint, which takes WAV or raw PCM, so on that path you convert first. Converting every note to 16 kHz mono WAV with ffmpeg has a second benefit: the duration is right there in the WAV header, so your server can check it without another tool or a network call.
import shutil
import subprocess
import wave
def to_wav(source_path: str, target_path: str) -> None:
"""Normalize any incoming voice note to 16 kHz mono 16-bit WAV."""
if shutil.which("ffmpeg") is None:
raise RuntimeError("ffmpeg not found: install it (brew install ffmpeg or apt install ffmpeg).")
subprocess.run(
["ffmpeg", "-i", source_path, "-ar", "16000", "-ac", "1",
"-c:a", "pcm_s16le", "-y", target_path],
check=True,
capture_output=True,
)
def duration_ms(wav_path: str) -> int:
"""Read the duration from the WAV header; no network call needed."""
with wave.open(wav_path, "rb") as w:
return int(w.getnframes() * 1000 / w.getframerate())Here’s the upload endpoint that ties it together. It saves the incoming file, then hands it to transcribe_note(), which converts it, checks it, and routes it (you’ll see that function in the routing section below):
"""Minimal upload endpoint: POST a voice note, get the transcript back."""
import os
import tempfile
from assemblyai.sync.v1 import SyncTranscriber, SyncTranscriptError
from flask import Flask, jsonify, request
from voicenotes import api_key, transcribe_note
KEY = api_key()
app = Flask(__name__)
transcriber = SyncTranscriber(api_key=KEY)
@app.post("/voice-notes")
def upload_voice_note():
upload = request.files["audio"]
suffix = os.path.splitext(upload.filename or "")[1] or ".m4a"
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "note" + suffix)
upload.save(path)
try:
return jsonify(transcribe_note(path, transcriber, KEY))
except SyncTranscriptError as error:
return jsonify({"status": "failed", "error_code": error.error_code}), 502
if __name__ == "__main__":
transcriber.warm() # open the connection before the first upload arrives
app.run(port=8000)Two guards are worth adding before any request, because both failure modes are common and both are cheap to catch locally:
- Duration under 80 ms. Users fat-finger the mic button constantly. On /v1/transcribe these return a 400 with the title Audio Too Short, and there’s no reason to spend a round trip discovering that.
- Duration over 120 seconds. Some people record five-minute voice notes. The SDK path rejects anything past 120 s with a 413, so those notes need the HTTP endpoint or a pre-recorded job. See the routing section below.
Step 2: Transcribe it
With the Python SDK, this is the entire integration:
import os
import sys
from assemblyai.sync.v1 import SyncTranscriber, SyncTranscriptionConfig
api_key = os.environ.get("ASSEMBLYAI_API_KEY") or sys.exit("Set ASSEMBLYAI_API_KEY")
config = SyncTranscriptionConfig(model="universal-3-6-pro")
transcriber = SyncTranscriber(api_key=api_key, config=config)
transcriber.warm() # open the connection as soon as you know a note is coming
result = transcriber.transcribe("./voice_note.wav")
print(result.text)The same call with the JavaScript SDK:
import { AssemblyAI } from "assemblyai";
const apiKey = process.env.ASSEMBLYAI_API_KEY;
if (!apiKey) {
console.error("Set ASSEMBLYAI_API_KEY");
process.exit(1);
}
const client = new AssemblyAI({ apiKey });
await client.sync.warm(); // open the connection as soon as you know a note is coming
const result = await client.sync.transcribe("./voice_note.wav", {
model: "universal-3-6-pro",
});
console.log(result.text);Set model to universal-3-6-pro explicitly. The SDKs still default to universal-3-5-pro, which is retired for Sync, and requests that use it get routed to Universal-3.6 Pro anyway. Call warm() as soon as you know audio is coming, for example when the user presses record, so the TLS handshake is done before the upload arrives. The connection pre-warming guide covers how long a warmed connection stays useful.
Or over plain HTTP, if you’d rather not add an SDK. This path posts the phone’s original m4a with no conversion, and the X-AAI-Model header is required on every request:
import os
import sys
import requests
api_key = os.environ.get("ASSEMBLYAI_API_KEY") or sys.exit("Set ASSEMBLYAI_API_KEY")
# /v1/transcribe takes the phone's original file: no conversion needed.
with open("voice_note.m4a", "rb") as f:
response = requests.post(
"https://sync.assemblyai.com/v1/transcribe",
headers={
"Authorization": api_key,
"X-AAI-Model": "universal-3-6-pro",
},
files={"audio": ("voice_note.m4a", f, "audio/mp4")},
timeout=60,
)
response.raise_for_status()
result = response.json()
print(result["text"])You get back the transcript, per-word confidence scores, an overall confidence value, the audio duration, a session_id, and the server-side processing time. An example response:
{
"text": "Hey, running about ten minutes late. Start without me.",
"words": [
{ "text": "Hey", "confidence": 0.98 },
{ "text": "running", "confidence": 0.96 }
],
"confidence": 0.97,
"audio_duration_ms": 3120,
"session_id": "eb92c4ff-4bbb-429f-9b99-7279d7fe738f",
"request_time_ms": 141.6
}Log the session_id for every request. It’s the first thing support asks for. Word-level start and end times are opt-in (timestamps=True) if your player highlights words as the note plays.
The model behind every Sync request is Universal-3.6 Pro. If you want the base call in isolation before wiring it into your upload handler, the Sync STT quickstart walks through it.
POST the audio and get the finished transcript back in the same response, with no job IDs and no polling. Start with a free API key.
Step 3: Render it in the right place
This is a product decision more than an engineering one, and it’s where most implementations go wrong.
Treat the transcript as a preview of the voice note, with the audio still one tap away. The pattern that works: the waveform stays, the transcript appears beneath it as collapsed text with a “show more” affordance, and playback still works. The user decides whether reading is enough.
Where it gets interesting is when you transcribe. Two options:
On send. The sender’s client uploads, you transcribe immediately, and the note arrives with text already attached. You pay for a transcription on every note, including the ones nobody opens, but the recipient never waits.
On open. You transcribe the first time a recipient views the thread. That saves money if a meaningful share of notes go unread, and because the transcript comes back in the same request, the wait is short enough that most users won’t notice it.
For most messaging products, on-open wins on spend and loses nothing perceptible. For products where notes are searchable (a productivity app, a CRM, anything with a search bar over message history), transcribe on send, because you need the text whether or not anyone opened the message.
Want to see it work? Get a free API key or drop a voice note into the Sync Playground.
Step 4: Handle multilingual inboxes
Voice notes are where multilingual products stop being able to pretend everyone speaks English. A user’s inbox holds whatever languages their contacts speak, often several within one thread.
language_codes takes a list: one code for monolingual audio, or several for multilingual audio that switches languages mid-note. The Sync API accepts 32 language codes, and a code outside that set returns a 400 that lists the full set. Over raw HTTP the same field goes in the JSON config part.
import os
import sys
from assemblyai.sync.v1 import SyncTranscriber, SyncTranscriptionConfig
api_key = os.environ.get("ASSEMBLYAI_API_KEY") or sys.exit("Set ASSEMBLYAI_API_KEY")
transcriber = SyncTranscriber(api_key=api_key)
# You know this user's threads are in Spanish and English.
config = SyncTranscriptionConfig(model="universal-3-6-pro", language_codes=["es", "en"])
result = transcriber.transcribe("./voice_note.wav", config=config)
print(result.text)In JavaScript:
import { AssemblyAI } from "assemblyai";
const apiKey = process.env.ASSEMBLYAI_API_KEY;
if (!apiKey) {
console.error("Set ASSEMBLYAI_API_KEY");
process.exit(1);
}
const client = new AssemblyAI({ apiKey });
// You know this user's threads are in Spanish and English.
const result = await client.sync.transcribe("./voice_note.wav", {
model: "universal-3-6-pro",
language_codes: ["es", "en"],
});
console.log(result.text);If your app already knows something about the conversation, such as the participants’ locales or the language of the last twenty text messages in the thread, feed that in rather than guessing globally. You almost always have better signal than a language-agnostic default. Leave language_codes out and no language steering is applied.
Record forty seconds the way your users talk, with names, slang, and a language switch mid-thread, and see what comes back. No setup required.
Step 5: Backfill the notes you already have
Shipping this feature to an existing product means every user immediately asks the same question: what about all my old voice notes?
Backfilling is a bounded, one-time job, and it’s mostly about being polite to the API. Run notes concurrently, cap the concurrency, and honor the backpressure signals. The SDK’s AsyncSyncTranscriber keeps the whole job on one event loop:
"""Backfill transcripts for voice notes already on disk, newest first.
usage: python backfill.py <folder of 16 kHz WAV notes up to 120 s>
"""
import asyncio
import sys
from dataclasses import dataclass
from pathlib import Path
from assemblyai.sync.v1 import (
AsyncSyncTranscriber,
SyncTranscriptError,
SyncTranscriptionConfig,
)
from voicenotes import SYNC_MODEL, api_key
@dataclass
class Note:
id: str
path: str
CONFIG = SyncTranscriptionConfig(model=SYNC_MODEL)
async def transcribe_one(transcriber, note, semaphore):
async with semaphore:
for attempt in range(3):
try:
result = await transcriber.transcribe(note.path, config=CONFIG)
return note.id, result.text
except SyncTranscriptError as error:
transient = error.status_code in (429, 503) or (
error.status_code in (500, 504) and attempt == 0
)
if transient and attempt < 2:
await asyncio.sleep(error.retry_after or 2 ** attempt)
continue
print(f"{note.id}: {error.status_code} {error.error_code}", file=sys.stderr)
return note.id, None # mark the row, move on
async def backfill(notes):
semaphore = asyncio.Semaphore(10) # 429s mean lower it; default limit is 200 req/min
async with AsyncSyncTranscriber(api_key=api_key()) as transcriber:
return await asyncio.gather(
*(transcribe_one(transcriber, n, semaphore) for n in notes)
)
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("usage: python backfill.py <folder of WAV notes>")
files = sorted(Path(sys.argv[1]).glob("*.wav"), key=lambda p: p.stat().st_mtime, reverse=True)
notes = [Note(id=p.stem, path=str(p)) for p in files]
for note_id, text in asyncio.run(backfill(notes)):
print(note_id, "->", text)Four things that make a backfill go smoothly:
- Respect Retry-After on 429 and 503. The SDK error carries it as retry_after. Exponential backoff that ignores the header keeps you rate-limited for longer. The default rate limit is 200 requests per minute per account, shared by every API key on it.
- Retry 500 and 504 once, and never retry 400, 413, or 415. Those three mean the audio or config is wrong. Fix the file and resubmit it; the error-handling guide lists every status.
- Never fail the whole batch on one bad note. Some of your archived audio is corrupt, zero-length, or in a format nobody remembers supporting. Log the error code, mark the row, and move on.
- Backfill newest-first. Users open recent threads. A backfill that starts at the beginning of time finishes the part anyone cares about last.
What about notes longer than two minutes
Some users record five-minute voice notes, and your product needs a path for them.
The two-minute ceiling belongs to the SDK path. A note between 120 seconds and 20 minutes can still go through the Sync API: post the finished file to /v1/transcribe over HTTP and the transcript comes back in the same response. Past 20 minutes, submit a pre-recorded job on AssemblyAI-STT-3.7, the flagship model for recorded audio, and collect the result with a webhook. Pre-recorded jobs also give you speaker diarization and the rest of the Speech Understanding features, which the Sync API doesn’t offer. That matters for a long recording with more than one voice on it. Adding universal-2 to the model list covers languages outside AssemblyAI-STT-3.7’s set.
The routing is three thresholds:
SYNC_MODEL = "universal-3-6-pro" # Sync runs on Universal-3.6 Pro
SYNC_URL = "https://sync.assemblyai.com/v1/transcribe"
MIN_MS = 80 # below this: Audio Too Short
SDK_MAX_MS = 120_000 # SDK path (/v1/transcribe/live) cap
HTTP_MAX_MS = 20 * 60_000 # HTTP /v1/transcribe cap
def sync_transcribe_http(wav_path: str, key: str) -> str:
"""120 s to 20 min: POST the finished file to /v1/transcribe over HTTP."""
with open(wav_path, "rb") as f:
response = requests.post(
SYNC_URL,
headers={"Authorization": key, "X-AAI-Model": SYNC_MODEL},
files={"audio": ("voice_note.wav", f, "audio/wav")},
timeout=60,
)
response.raise_for_status()
result = response.json()
print(f"session_id: {result['session_id']}")
return result["text"]
def submit_async(path: str, key: str, webhook_url=None) -> str:
"""Over 20 min: submit a pre-recorded job on AssemblyAI-STT-3.7."""
config = aai.TranscriptionConfig(
speech_models=["assemblyai-stt-3-7", "universal-2"],
webhook_url=webhook_url,
)
transcript = aai.Transcriber(api_key=key, config=config).submit(path)
return transcript.id
def transcribe_note(source_path: str, transcriber: SyncTranscriber, key: str) -> dict:
wav_path = os.path.splitext(source_path)[0] + ".16k.wav"
to_wav(source_path, wav_path)
ms = duration_ms(wav_path)
if ms < MIN_MS:
return {"status": "skipped", "reason": "too_short", "duration_ms": ms}
if ms <= SDK_MAX_MS:
return {"status": "done", "text": sync_transcribe(transcriber, wav_path)}
if ms <= HTTP_MAX_MS:
return {"status": "done", "text": sync_transcribe_http(wav_path, key)}
return {"status": "pending", "job_id": submit_async(wav_path, key)}Your UI can be honest about the difference. Short notes get text immediately, and a very long note shows a “transcribing” state until the webhook lands. Nobody who records a half-hour voice note expects instant anything. For a side-by-side of the two job styles, see real-time vs. batch transcription.
The thing nobody tells you about voice notes
Once the text exists, your product changes in a way that’s easy to miss.
Voice notes have historically been a black hole in every product that supports them: unsearchable, unquotable, unlinkable, invisible to every feature you’ve built on top of text. Transcribe them and they join the rest of your product. They show up in search. They can be replied to with a quote. They can be summarized, translated, or turned into a task, the same downstream moves any other speech-to-text output supports.
The transcription is a two-day build. What it makes possible is the part worth planning for, and it’s a good argument for transcribing on send rather than on open, even where on-open spends less. If the feature you’re building is closer to dictation (the user speaks, then edits polished text), compare the two products in Sync API or Dictation API.
A two-day build, and every voice note in your product becomes searchable text. Get a free API key and start.
Frequently Asked Questions (FAQs)
What audio formats does the Sync API accept for voice notes?
Over HTTP, POST /v1/transcribe accepts WAV, raw PCM, AAC, MP3, M4A, Ogg/Opus, FLAC, and WebM, so a phone’s m4a or WebM file goes in as is. The Python and JavaScript SDKs send audio through /v1/transcribe/live, which accepts only 16-bit WAV or raw PCM, so convert first; a one-line ffmpeg call to 16 kHz mono WAV covers it.
How long can a voice note be?
Between 80 milliseconds and 20 minutes, up to 256 MB, on the HTTP /v1/transcribe endpoint. The SDKs cap audio at 120 seconds. For recordings longer than 20 minutes, submit a pre-recorded job on AssemblyAI-STT-3.7.
Which model does the Sync API use?
Universal-3.6 Pro. Send it as the X-AAI-Model: universal-3-6-pro header over HTTP, or set model="universal-3-6-pro" in the SDK config. Requests that still name universal-3-5-pro are routed to Universal-3.6 Pro.
Should I transcribe voice notes when they’re sent or when they’re opened?
Transcribe on open if you’re optimizing spend and notes often go unread. Transcribe on send if voice notes need to be searchable, since you need the text whether or not anyone opened the message.
Can I transcribe voice notes in multiple languages?
Yes. language_codes accepts one code for monolingual audio or a list for multilingual audio, across 32 supported languages. Feed in whatever locale signal your app already has rather than guessing.
How do I transcribe a backlog of existing voice notes?
Run them concurrently with a capped semaphore, stay under the 200-requests-per-minute default rate limit, honor Retry-After on 429 and 503 responses, and let individual failures fall through to a log instead of failing the batch. Process newest-first so recent threads become useful immediately.
What happens if a user taps the mic button by accident?
On /v1/transcribe, clips under 80 milliseconds return a 400 with the title Audio Too Short. Check the duration on your server and skip the request rather than surfacing an error for a note nobody meant to send.