Choose live captions when you need words as someone speaks, or fast file transcription when you need speaker labels and timestamps after a recording. This local Gradio app lets you try both with MAI-Transcribe-2 models. It's for Python developers adding transcription to meeting, media, or captioning apps. Use recordings you have permission to process.
After completing this recipe, you can:
- Configure a file transcription request with speaker labels and timestamps.
- Compare transcripts with and without a phrase-list hint.
- Interpret provisional and committed captions in a streaming response.
Watch the app transcribe a meeting
Watch the app transcribe a meeting as it plays. Then see how to save the recording and transcribe it again as a file, with labels identifying each speaker.
The video has audio and English captions.
Download the walkthrough with audio.
Scenarios to try
Explore the scenarios highlighted in the MAI-Transcribe-2 announcement:
- Meetings, interviews, and recorded calls: review speaker turns and domain-specific terms in a transcript.
- Media and recorded presentations: use word timestamps to locate speech in the recording.
- Live speech: watch provisional captions appear and change while a person speaks.
Choose an interface
| Need | Interface | Result |
|---|---|---|
| A completed recording with speaker labels or timestamps | Fast transcription | A transcript with optional speaker and timing information |
| Captions while someone speaks | Realtime API | Provisional and committed text as audio streams |
Streaming is in public preview without an SLA and isn't recommended for production workloads. This app doesn't measure accuracy or latency; compare its results with your own audio instead.
Before you start
Estimated time, approximate:
Setup: 15 to 25 minutes to create the resource and streaming deployment and install dependencies. A clean dependency install took about 3 minutes in testing.
App walkthrough: about 10 minutes.
Optional API examples: about 5 minutes, including about 31 seconds of streaming.
Open this notebook from the Forgebook
notebooks/directory with Python 3.11 or later and Jupyter. Itsdata/mai-transcribe-2/folder contains the app, the sample recording, and the dependencies.Create a Microsoft Foundry resource for Speech or use one you already have. For file transcription, choose a region marked as supported in the Transcribe with MAI-Transcribe column of the Speech service regions table. The currently listed resource regions are
centralindia,centralus,eastus,northeurope,southeastasia,swedencentral,westeurope,westus, andwestus2. For live transcription, deploy MAI-Transcribe-2-Streaming and follow its availability guide, which listscentralus,eastus2,southeastasia, andswedencentralas serving regions. This streaming serving-region list is distinct from the file model's resource-region list. Each path needs its endpoint and API key; both models can use the same resource when its region supports both.
Authentication: MAI-Transcribe-2 supports both API keys and keyless Microsoft Entra ID authentication. This recipe uses API keys only for demonstration purposes; prefer Microsoft Entra ID for production workloads. To set it up, see Configure Microsoft Entra authentication.
Find the endpoint, key, and deployment
In the Azure portal, open your resource and select Keys and Endpoint; use its resource endpoint and a key for the app. For live audio, open your project in the Foundry portal, select Build > Models > Deploy a base model, find MAI-Transcribe-2-Streaming, and select Deploy. Note the deployment name on the Models page. The fast transcription API selects its model in the request and doesn't need a separate model deployment.
Alternatively, in Bash with the Azure CLI signed in to the correct subscription, replace the two values below. The commands get the resource endpoint and key and list streaming deployments:
RESOURCE_GROUP="<resource-group>"
RESOURCE_NAME="<resource-name>"
MAI_ENDPOINT="<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><mi>a</mi><mi>z</mi><mi>c</mi><mi>o</mi><mi>g</mi><mi>n</mi><mi>i</mi><mi>t</mi><mi>i</mi><mi>v</mi><mi>e</mi><mi>s</mi><mi>e</mi><mi>r</mi><mi>v</mi><mi>i</mi><mi>c</mi><mi>e</mi><mi>s</mi><mi>a</mi><mi>c</mi><mi>c</mi><mi>o</mi><mi>u</mi><mi>n</mi><mi>t</mi><mi>s</mi><mi>h</mi><mi>o</mi><mi>w</mi><mo>−</mo><mo>−</mo><mi>r</mi><mi>e</mi><mi>s</mi><mi>o</mi><mi>u</mi><mi>r</mi><mi>c</mi><mi>e</mi><mo>−</mo><mi>g</mi><mi>r</mi><mi>o</mi><mi>u</mi><mi>p</mi><mi mathvariant="normal">"</mi></mrow><annotation encoding="application/x-tex">(az cognitiveservices account show --resource-group "</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="katex-base"><span class="katex-strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.044em;">z</span><span class="mord mathnormal">co</span><span class="mord mathnormal" style="margin-right:0.0359em;">g</span><span class="mord mathnormal">ni</span><span class="mord mathnormal">t</span><span class="mord mathnormal">i</span><span class="mord mathnormal" style="margin-right:0.0359em;">v</span><span class="mord mathnormal" style="margin-right:0.0278em;">eser</span><span class="mord mathnormal" style="margin-right:0.0359em;">v</span><span class="mord mathnormal">i</span><span class="mord mathnormal">ces</span><span class="mord mathnormal">a</span><span class="mord mathnormal">cco</span><span class="mord mathnormal">u</span><span class="mord mathnormal">n</span><span class="mord mathnormal">t</span><span class="mord mathnormal">s</span><span class="mord mathnormal">h</span><span class="mord mathnormal">o</span><span class="mord mathnormal" style="margin-right:0.0269em;">w</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="katex-base"><span class="katex-strut" style="height:0.6667em;vertical-align:-0.0833em;"></span><span class="mord">−</span><span class="mord mathnormal" style="margin-right:0.0278em;">r</span><span class="mord mathnormal">eso</span><span class="mord mathnormal">u</span><span class="mord mathnormal" style="margin-right:0.0278em;">r</span><span class="mord mathnormal">ce</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="katex-base"><span class="katex-strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">g</span><span class="mord mathnormal" style="margin-right:0.0278em;">r</span><span class="mord mathnormal">o</span><span class="mord mathnormal">u</span><span class="mord mathnormal">p</span><span class="mord">"</span></span></span></span>RESOURCE_GROUP" --name "$RESOURCE_NAME" --query properties.endpoint -o tsv)"
MAI_API_KEY="<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><mi>a</mi><mi>z</mi><mi>c</mi><mi>o</mi><mi>g</mi><mi>n</mi><mi>i</mi><mi>t</mi><mi>i</mi><mi>v</mi><mi>e</mi><mi>s</mi><mi>e</mi><mi>r</mi><mi>v</mi><mi>i</mi><mi>c</mi><mi>e</mi><mi>s</mi><mi>a</mi><mi>c</mi><mi>c</mi><mi>o</mi><mi>u</mi><mi>n</mi><mi>t</mi><mi>k</mi><mi>e</mi><mi>y</mi><mi>s</mi><mi>l</mi><mi>i</mi><mi>s</mi><mi>t</mi><mo>−</mo><mo>−</mo><mi>r</mi><mi>e</mi><mi>s</mi><mi>o</mi><mi>u</mi><mi>r</mi><mi>c</mi><mi>e</mi><mo>−</mo><mi>g</mi><mi>r</mi><mi>o</mi><mi>u</mi><mi>p</mi><mi mathvariant="normal">"</mi></mrow><annotation encoding="application/x-tex">(az cognitiveservices account keys list --resource-group "</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="katex-base"><span class="katex-strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.044em;">z</span><span class="mord mathnormal">co</span><span class="mord mathnormal" style="margin-right:0.0359em;">g</span><span class="mord mathnormal">ni</span><span class="mord mathnormal">t</span><span class="mord mathnormal">i</span><span class="mord mathnormal" style="margin-right:0.0359em;">v</span><span class="mord mathnormal" style="margin-right:0.0278em;">eser</span><span class="mord mathnormal" style="margin-right:0.0359em;">v</span><span class="mord mathnormal">i</span><span class="mord mathnormal">ces</span><span class="mord mathnormal">a</span><span class="mord mathnormal">cco</span><span class="mord mathnormal">u</span><span class="mord mathnormal">n</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.0315em;">k</span><span class="mord mathnormal" style="margin-right:0.0359em;">ey</span><span class="mord mathnormal">s</span><span class="mord mathnormal" style="margin-right:0.0197em;">l</span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="katex-base"><span class="katex-strut" style="height:0.6667em;vertical-align:-0.0833em;"></span><span class="mord">−</span><span class="mord mathnormal" style="margin-right:0.0278em;">r</span><span class="mord mathnormal">eso</span><span class="mord mathnormal">u</span><span class="mord mathnormal" style="margin-right:0.0278em;">r</span><span class="mord mathnormal">ce</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="katex-base"><span class="katex-strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.0359em;">g</span><span class="mord mathnormal" style="margin-right:0.0278em;">r</span><span class="mord mathnormal">o</span><span class="mord mathnormal">u</span><span class="mord mathnormal">p</span><span class="mord">"</span></span></span></span>RESOURCE_GROUP" --name "$RESOURCE_NAME" --query key1 -o tsv)"
export MAI_ENDPOINT MAI_API_KEY
az cognitiveservices account deployment list --resource-group "<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>R</mi><mi>E</mi><mi>S</mi><mi>O</mi><mi>U</mi><mi>R</mi><mi>C</mi><msub><mi>E</mi><mi>G</mi></msub><mi>R</mi><mi>O</mi><mi>U</mi><mi>P</mi><mi mathvariant="normal">"</mi><mo>−</mo><mo>−</mo><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi><mi mathvariant="normal">"</mi></mrow><annotation encoding="application/x-tex">RESOURCE_GROUP" --name "</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="katex-base"><span class="katex-strut" style="height:0.8444em;vertical-align:-0.15em;"></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mord mathnormal" style="margin-right:0.0576em;">E</span><span class="mord mathnormal" style="margin-right:0.0576em;">S</span><span class="mord mathnormal" style="margin-right:0.0278em;">O</span><span class="mord mathnormal" style="margin-right:0.109em;">U</span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mord mathnormal" style="margin-right:0.0715em;">C</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.0576em;">E</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3283em;"><span style="top:-2.55em;margin-left:-0.0576em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="katex-sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">G</span></span></span></span><span class="vlist-s"></span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.0077em;">R</span><span class="mord mathnormal" style="margin-right:0.0278em;">O</span><span class="mord mathnormal" style="margin-right:0.109em;">U</span><span class="mord mathnormal" style="margin-right:0.1389em;">P</span><span class="mord">"</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">−</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="katex-base"><span class="katex-strut" style="height:0.7778em;vertical-align:-0.0833em;"></span><span class="mord">−</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span><span class="mord">"</span></span></span></span>RESOURCE_NAME" --query "[?properties.model.name=='MAI-Transcribe-2-Streaming'].name" -o tsv
The list command finds existing deployments; create one in Foundry first if
the list is empty. For the API examples, export MAI_STREAMING_DEPLOYMENT
with the deployment name if it differs from MAI-Transcribe-2-Streaming.
If streaming uses a different resource, repeat the endpoint and key lookup
for that resource and export them as MAI_STREAMING_ENDPOINT and
MAI_STREAMING_API_KEY. Start Jupyter from the same shell so the kernel
inherits these variables. For the app, enter the endpoint, key, and deployment
name in Settings; shell variables are for the API examples only.
See the CLI references for accounts,
keys,
and deployments.
Don't print or share keys, enable shell tracing, or save keys in the notebook.
- Use recordings you have permission to process and obtain any required consent. The app sends audio to Azure. Enter keys in the app, not in the notebook or source files.
NoteApp transcription requests are billed. Check current pricing before submitting audio.
Install the app dependencies and PyAV, which prepares the sample recording for the optional API examples.
%pip install -r data/mai-transcribe-2/requirements.txt avExpected output: pip reports installed or already-satisfied packages.
Launch the local Gradio app
Run the next cell to launch the app inline in the notebook; Gradio also provides a local URL if you prefer a separate browser tab. Open Settings on the left. The next cell displays the app and a local URL. Under Model configuration, enter the endpoint and API key for the model you want to use. If your streaming deployment has a custom name, enter that name under MAI-Transcribe-2-Streaming.
- Live speech: select the microphone, wait for the connection, and speak. Stop to finish the transcript. Select Download recording to save a WAV that you can also submit as a file.
- Recorded audio: attach a WAV, MP3, or FLAC file of up to 25 MiB. Open Options on the right to choose Speaker labels, Word timestamps, or Key phrases such as names and product terms. Select the up arrow to submit it. Separate key phrases with commas or newlines.
Compare the transcript, speaker turns, and times with the source audio. Try the settings that matter for your scenario. Attaching a file alone doesn't send a request.
# Displays the app inline; it prints no output of its own.
import sys
from pathlib import Path
APP_DIR = Path("data/mai-transcribe-2").resolve()
if str(APP_DIR) not in sys.path:
sys.path.insert(0, str(APP_DIR))
from app import MAX_UPLOAD_BYTES, build_app # noqa: E402
demo = build_app()
demo.launch(
server_name="127.0.0.1",
share=False,
inline=True,
prevent_thread_lock=True,
show_error=False,
max_file_size=MAX_UPLOAD_BYTES,
)Explore the APIs with the sample
The walkthrough and saved results show the sample without requiring you to run these cells. To explore the requests behind the app, run the optional examples below. They use the fast transcription API for the file and the Realtime API for streaming. Outputs can vary between runs.
Before running the API examples
- The examples use API keys, like the app. Set
MAI_API_KEYto a key from the Speech resource's Keys and Endpoint page in the Azure portal. If streaming uses another resource, also setMAI_STREAMING_API_KEY. - Set
MAI_ENDPOINTto the Speech resource's HTTPS base endpoint, for examplehttps://<resource>.services.ai.azure.com. - For the streaming example, deploy MAI-Transcribe-2-Streaming. If its
deployment name differs, set
MAI_STREAMING_DEPLOYMENT; if it's on another resource, setMAI_STREAMING_ENDPOINTto that resource's base endpoint. Use the portal or CLI steps above to find these values.
The examples use the fast transcription REST API and the Realtime API.
Running all the examples sends three file requests and streams the 31-second sample once. Those requests are billed separately from app requests.
The next cell decodes the bundled meeting_b.m4a to a temporary mono 16-kHz
PCM WAV. The cleanup step at the end removes it. recipe_helpers.py handles
the conversion and shortens printed transcript lines.
import json
import os
import sys
import wave
from pathlib import Path
from urllib.parse import urlsplit
import requests
DATA_DIR = Path("data/mai-transcribe-2/")
sys.path.insert(0, str(DATA_DIR.resolve()))
from recipe_helpers import excerpt, prepare_recording # noqa: E402
session_files, AUDIO = prepare_recording(DATA_DIR / "meeting_b.m4a")
with wave.open(str(AUDIO), "rb") as audio:
print(
f"Prepared: {audio.getnframes() / audio.getframerate():.3f}s, "
f"{audio.getframerate()} Hz, {audio.getnchannels()} channel"
)Prepared: 31.221s, 16000 Hz, 1 channel
Expected output: Prepared: 31.221s, 16000 Hz, 1 channel. Read the sample transcript. Recording source: Microsoft AI.
Who said what: speaker diarization
The fast transcription API
accepts the audio and a JSON definition as multipart form data.
enhancedMode.enabled and enhancedMode.model select MAI-Transcribe-2; both
are required, and no model deployment is needed. with_options adds the
model options used below. This cell reads the key and defines the helpers without
sending a request.
def resource_root(variable):
value = os.environ[variable].strip()
parsed = urlsplit(value)
host = parsed.hostname or ""
if (
parsed.scheme != "https"
or parsed.netloc.lower() != host
or parsed.path not in ("", "/")
or parsed.query
or parsed.fragment
or not host.endswith((".services.ai.azure.com", ".cognitiveservices.azure.com"))
):
raise ValueError(f"{variable} must be an HTTPS Speech resource base endpoint.")
return f"https://{host}"
ENDPOINT = resource_root("MAI_ENDPOINT")
API_KEY = os.environ["MAI_API_KEY"].strip()
BASE = {"enhancedMode": {"enabled": True, "model": "MAI-Transcribe-2"}}
def transcribe(definition):
with AUDIO.open("rb") as audio:
response = requests.post(
f"{ENDPOINT}/speechtotext/transcriptions:transcribe",
params={"api-version": "2025-10-15"},
headers={"Ocp-Apim-Subscription-Key": API_KEY},
files={"audio": (AUDIO.name, audio, "audio/wav")},
data={"definition": json.dumps(definition)},
timeout=(10, 180),
allow_redirects=False,
)
if response.status_code in range(300, 400):
raise RuntimeError("Speech returned an unexpected redirect; check the resource endpoint.")
response.raise_for_status()
return response.json()
def with_options(**options):
return {"enhancedMode": {**BASE["enhancedMode"], "modelOptions": options}}
print("Speech request helpers ready; no request sent.")Speech request helpers ready; no request sent.
One request returns a transcript with clean text for reading, speaker
labels from diarization, segment timestamps for each turn, and a
phrase list with a term from this meeting, "sign-off". The next sections
reuse meeting_definition and change one option at a time.
meeting_definition = {
**with_options(transcribeStyle="clean", timestamps="segment"),
"diarization": {"enabled": True},
"phraseList": {"phrases": ["sign-off"]},
}
meeting = transcribe(meeting_definition)
meeting_text = meeting["combinedPhrases"][0]["text"]
if not meeting_text.strip():
raise ValueError("Speech returned an empty transcript.")
print("Audio seconds:", round(meeting["durationMilliseconds"] / 1000))
print("Detected language:", meeting["phrases"][0]["locale"])
for phrase in meeting["phrases"]:
seconds = phrase["offsetMilliseconds"] / 1000
print(f"[{seconds:05.1f}s] Speaker {phrase['speaker']}: {excerpt(phrase['text'], 6)}")Audio seconds: 31 Detected language: en [001.5s] Speaker 0: let's start with the Q3 budget ... [010.3s] Speaker 1: I did. The travel line item ... [017.1s] Speaker 0: Yeah, sure. I think two of ... [024.9s] Speaker 1: Agreed. Okay, well, let's flag it ...
Expected output: 31 audio seconds, detected language en, and turns from speakers 0 and 1, each with its start time. Exact wording, segment boundaries, and labels can vary between runs. Speaker IDs are labels within this response, not names. Check words, speakers, and times against the recording.
| Symptom | Likely cause | Fix |
|---|---|---|
| 401 or 403 | The key doesn't match the endpoint's resource, or key-based access is disabled | Copy the key and endpoint from the same resource; enable key-based access |
| Enhanced mode rejected | The resource region doesn't support MAI-Transcribe | Use a supported region from the regions table |
| Streaming connection fails | Wrong endpoint or deployment name | Check MAI_STREAMING_ENDPOINT and MAI_STREAMING_DEPLOYMENT; reconnect before sending more audio |
| Empty transcript or no word timestamps | The audio has no speech, or the request options changed | Check the recording and the definition options |
See Speech authentication troubleshooting.
Time every word
Switch timestamps to word for word-level playback highlighting. Offsets
are milliseconds from the start of the audio.
words = transcribe({**meeting_definition, **with_options(transcribeStyle="clean", timestamps="word")})
timed_words = [word for phrase in words["phrases"] for word in phrase.get("words", [])]
if not timed_words:
raise ValueError("Speech returned no word timestamps.")
print("Words with timestamps:", len(timed_words))
for word in timed_words[:3]:
print(f"{word['text']}: {word['offsetMilliseconds']} ms")Words with timestamps: 74 let's: 1520 ms start: 1920 ms with: 2200 ms
Expected output: 74 words have timestamps; the first three start at 1520, 1920, and 2200 ms. Timing is an estimate and can vary between requests.
Spell your terms: phrase-list biasing
Send the same request without its phrase list and compare the term.
baseline = transcribe({key: value for key, value in meeting_definition.items() if key != "phraseList"})
for label, text in (("Without hint", baseline["combinedPhrases"][0]["text"]), ("With hint", meeting_text)):
print(f"{label} contains 'sign-off':", "sign-off" in text.lower())Without hint contains 'sign-off': False With hint contains 'sign-off': True
Expected output: false without the hint and true with it: the hint changes the spelling to "sign-off" in this run. A hint raises a term's likelihood; it doesn't force output. Test your own meetings' terms against the audio.
Watch live captions correct themselves
MAI-Transcribe-2-Streaming returns words while someone is still speaking. Its Realtime API, in public preview without an SLA, uses an OpenAI Realtime API–style WebSocket protocol; see the Realtime API guide. A session works like this:
- A
session.updatemessage names the deployment and the audio format. Speaker labels, timestamps, and phrase lists are file options; streaming doesn't take them. input_audio_buffer.appendmessages send base64 PCM16 mono audio, andinput_audio_buffer.commitasks for the final transcript.- An
intermediateevent carries a provisional guess that can still change; replace the previous one. Adeltaevent carries words that won't change; append it. Acompletedevent carries the final text.
This cell defines the session message and a client that streams the meeting at its real pace, recording each caption as committed and provisional text. It doesn't connect.
import asyncio
import base64
from websockets.asyncio.client import connect
STREAM_DEPLOYMENT = os.environ.get("MAI_STREAMING_DEPLOYMENT", "MAI-Transcribe-2-Streaming")
EVENT = "conversation.item.input_audio_transcription."
def streaming_session(deployment):
return {
"type": "session.update",
"session": {
"type": "transcription",
"audio": {
"input": {
"format": {"type": "audio/pcm", "rate": 16_000},
"transcription": {"model": deployment},
"turn_detection": None,
}
},
},
}
async def next_event(websocket):
event = json.loads(await websocket.recv())
if event["type"] in ("error", f"{EVENT}failed"):
raise RuntimeError(f"Realtime API error: {event.get('error', {}).get('code', 'unknown')}")
return event
async def send_audio(websocket, chunk_ms=100):
with wave.open(str(AUDIO), "rb") as audio:
frames = audio.getframerate() * chunk_ms // 1000
while chunk := audio.readframes(frames):
await websocket.send(
json.dumps({"type": "input_audio_buffer.append", "audio": base64.b64encode(chunk).decode()})
)
await asyncio.sleep(chunk_ms / 1000)
await websocket.send(json.dumps({"type": "input_audio_buffer.commit"}))
async def stream_meeting(deployment):
root = resource_root("MAI_STREAMING_ENDPOINT") if "MAI_STREAMING_ENDPOINT" in os.environ else ENDPOINT
resource = urlsplit(root).hostname.split(".")[0]
url = f"wss://{resource}.services.ai.azure.com/mai/v1/realtime?intent=transcription"
key = os.environ.get("MAI_STREAMING_API_KEY", "").strip() or API_KEY
committed, captions = "", []
async with asyncio.timeout(120), connect(url, additional_headers={"api-key": key}) as websocket:
for expected in ("session.created", "session.updated"):
if expected == "session.updated":
await websocket.send(json.dumps(streaming_session(deployment)))
if (event := await next_event(websocket))["type"] != expected:
raise RuntimeError(f"Expected {expected}, received {event['type']}.")
sender = asyncio.create_task(send_audio(websocket))
try:
while True:
event = await next_event(websocket)
kind = event["type"].removeprefix(EVENT)
if kind == "delta":
committed += event["delta"]
elif kind == "intermediate":
caption = (committed, event.get("intermediate") or "")
if caption[1] and caption != (captions[-1] if captions else None):
captions.append(caption)
elif kind == "completed":
await sender
return captions, event["transcript"]
finally:
sender.cancel()
print(json.dumps(streaming_session(STREAM_DEPLOYMENT), indent=2)){ "type": "session.update", "session": { "type": "transcription", "audio": { "input": { "format": { "type": "audio/pcm", "rate": 16000 }, "transcription": { "model": "MAI-Transcribe-2-Streaming" }, "turn_detection": null } } } }
Expected output: the session.update message with your deployment name
and a 16,000-Hz audio/pcm format, matching the converted recording.
Stream the meeting. Each line shows one caption update: text before the vertical bar is committed, and text after it is still provisional. The loop prints updates until the first sentence commits, then the final transcript. Streaming takes about as long as the recording.
captions, final = await stream_meeting(STREAM_DEPLOYMENT)
first_sentence = next((i for i, (done, _) in enumerate(captions) if "." in done), len(captions) - 1)
for done, pending in captions[: first_sentence + 1]:
print(f"{done}|{pending}")
print("\nFinal:", excerpt(final, 12))|Let's |Let's start. |Let's start with |Let's start with the |Let's start with the Q2. |Let's start with the Q3 button. |Let's start with the Q3 budget. |Let's start with the Q3 budget review. Let's| start with the Q3 budget review. Let's start with| the Q3 budget review. Let's start with the| Q3 budget review. Let's start with the Q3 budget| review. Let's start with the Q3 budget review|. I sent Let's start with the Q3 budget review|. I sent the Let's start with the Q3 budget review.| I sent the update Final: Let's start with the Q3 budget review. I sent the updated spreadsheet ...
Expected output: provisional text grows and corrects itself before it
commits. In this run, "Q2." becomes "Q3 button.", then "Q3 budget.",
and only "Q3 budget review." moves to the committed side. Exact updates
vary between runs; the final transcript has no speaker labels or timestamps. In
data/mai-transcribe-2/app.py, MaiRealtimeStreamHandler applies the same
event rules to microphone audio.
What the sample shows
The saved results connect the objectives to three reusable patterns:
- Speaker labels and timestamps: use them when you review a completed recording. A file request separated two speakers and timed their turns and words.
- Phrase lists: use them when names or product terms are misheard. The comparison showed "sign-off" with a hint and not without it; hints increase likelihood but don't guarantee a word.
- Provisional and committed captions: use them when people need words while someone speaks. Streaming revised "Q2" to "Q3 budget" before committing the text; provisional captions can change, while committed text is retained.
The examples use two Azure Speech
interfaces: transcribe posts a definition to
the fast transcription API, and stream_meeting speaks the Realtime API's
session.update, append, and commit protocol.
To reuse the sample, copy these pieces from data/mai-transcribe-2/:
app.py:file_definitionbuilds file requests from app options, andMaiRealtimeStreamHandlerstreams microphone audio.recipe_helpers.py:prepare_recordingconverts audio to mono 16-kHz PCM WAV.- This notebook's
transcribeandstream_meetingcells: minimal request and streaming clients.
Tune it for your recordings
For a recorded file, open Options in the app and try these controls:
| Control | When to change it |
|---|---|
| Key phrases | Add names, products, and acronyms relevant to the recording. |
| Style | Choose Verbatim when fillers and false starts matter; the app defaults to Clean. |
| Speaker labels | Turn them on to distinguish speakers in a conversation. |
| Timestamps | Choose Word to see a time for each word, or Segment for each segment. |
| Language | Leave auto-detect on unless a known single-language recording is misdetected. |
Compare the result with your recording. Speaker labels and offsets show what
the service returned; they don't establish accuracy. For code experiments,
change meeting_definition or point prepare_recording at another file.
In app.py, file_definition maps the app controls to request options.
See the MAI parameter reference
for supported options and limits.
When you're finished, run the final cell. close_recipe() closes the app
and removes the converted WAV, even if you skipped the app
step. A forced kernel stop can leave temporary files behind.
def close_recipe():
try:
if "demo" in globals():
demo.close()
finally:
if "session_files" in globals():
session_files.cleanup()
close_recipe()
print("App and temporary recording closed.")App and temporary recording closed.
