DashboardPart 4Speech Services
💬 Part 4 · Topic 2 of 3

Speech Services

Azure AI Speech provides a complete audio AI platform — speech-to-text, text-to-speech, real-time speech translation, speaker recognition, and custom speech models. This topic covers all capabilities with Python code and exam decision guidance.

🐍 Python — every line explained ⏱️ ~40 min 🔥 High exam weight

Speech terms — defined before code

Speech-to-Text (STT)

Converting spoken audio into written text. Azure AI Speech provides two modes: real-time recognition (streaming audio from microphone or live source) and batch transcription (processing pre-recorded audio files stored in Blob Storage).

Text-to-Speech (TTS)

Converting written text into spoken audio. Azure AI Speech uses neural text-to-speech voices — AI-generated voices that sound natural. The SSML markup language lets you control prosody, pitch, speed, pauses, and emphasis.

Neural Voice

Azure's AI-generated text-to-speech voices that sound human-like. Azure provides hundreds of prebuilt neural voices across languages. You can also create a Custom Neural Voice trained on your own voice actor recordings.

SSML (Speech Synthesis Markup Language)

An XML-based markup language for controlling text-to-speech output. You can specify: voice name, language, speaking rate, pitch, volume, pauses, emphasis, and phonemes. Gives precise control over how text is spoken.

Speech Translation

Real-time translation of spoken words from one language to another. Audio in (English speech) → text out (translated to French text) or audio out (translated French speech). Different from Translator — this operates on audio, not text.

Speaker Recognition

Identifying who is speaking based on their unique vocal characteristics. Two types: Speaker Verification (is this person who they claim to be?) and Speaker Identification (which of these enrolled speakers is speaking?).

Speaker Verification

Verifying that a person's voice matches a previously enrolled voice profile. Returns a verification result: Accept or Reject + confidence score. Used for voice-based authentication ("voice is my password").

Speaker Identification

Determining which of a set of enrolled speakers is speaking. The system compares the incoming audio to a list of known speaker profiles and returns the best match. Used for meeting transcription with speaker attribution.

Custom Speech Model

A speech-to-text model fine-tuned on your specific domain vocabulary, accents, and acoustic conditions. If your application involves technical terms, proper nouns, or industry jargon that standard STT misrecognises — train a Custom Speech model.

Batch Transcription

Processing pre-recorded audio files at scale. Files are stored in Azure Blob Storage, you submit a transcription job, and results are written to output storage. Async — poll for job completion. Cheaper than real-time for offline processing.

SpeechConfig

The Python SDK object that configures the Speech service connection — subscription key, region, and default settings. Used for all Speech operations. Created with SpeechConfig(subscription=key, region=region).

AudioConfig

Specifies the audio source (microphone, audio file) or audio output (speaker, audio file) for Speech operations. AudioConfig.from_wav_file("file.wav") for file input. AudioConfig.from_default_microphone_input() for microphone.

Converting audio to text

📝
Analogy — A live court reporter vs a transcription service

Real-time STT is like a live court reporter — they listen and produce text word by word as people speak. Use for: live meetings, voice commands, real-time captioning.

Batch Transcription is like sending a recording to a transcription service — you upload the file, they process it overnight, send back the transcript. Use for: call recordings, podcast archives, interview recordings. Cheaper and handles long recordings.

Python — Speech-to-Text (from audio file)

Install: pip install azure-cognitiveservices-speech

import os
import azure.cognitiveservices.speech as speechsdk
# azure.cognitiveservices.speech is the Azure Speech SDK
# Commonly aliased as "speechsdk" for brevity


# ── Step 1: Configure the Speech service connection ────────────────────
# SpeechConfig holds your subscription key and region
# subscription=: your Azure AI Speech resource key
# region=: the Azure region e.g. "eastus", "canadacentral"
speech_config = speechsdk.SpeechConfig(
    subscription = os.environ.get("SPEECH_KEY"),
    region       = os.environ.get("SPEECH_REGION")
)

# Set the language the speaker is using (for recognition accuracy)
# Use BCP-47 format: "en-US", "fr-FR", "en-GB", "es-ES", etc.
speech_config.speech_recognition_language = "en-US"


# ── Step 2: Configure the audio source ─────────────────────────────────
# AudioConfig tells the SDK where to get the audio from
# from_wav_file(): read from a .wav file on disk
# from_default_microphone_input(): use the system's default microphone
audio_config = speechsdk.AudioConfig(
    filename = "meeting_recording.wav"
)


# ── Step 3: Create the SpeechRecognizer ────────────────────────────────
# SpeechRecognizer combines the speech config + audio config
# It is the main object that performs speech recognition
recognizer = speechsdk.SpeechRecognizer(
    speech_config = speech_config,
    audio_config  = audio_config
)


# ── Step 4: Recognize speech ────────────────────────────────────────────
# recognize_once() processes a single utterance (one sentence/phrase)
# It listens until a pause is detected, then returns the result
# For continuous long audio, use start_continuous_recognition() instead
result = recognizer.recognize_once()

# ── Step 5: Handle the result ───────────────────────────────────────────
# result.reason tells you what happened:
# ResultReason.RecognizedSpeech — audio was successfully transcribed
# ResultReason.NoMatch — audio detected but speech not recognizable
# ResultReason.Canceled — error occurred
if result.reason == speechsdk.ResultReason.RecognizedSpeech:
    print(f"Transcription: {result.text}")  # result.text is the transcribed text

elif result.reason == speechsdk.ResultReason.NoMatch:
    print("No speech recognised in the audio.")

elif result.reason == speechsdk.ResultReason.Canceled:
    # Get cancellation details to understand the error
    cancellation = speechsdk.CancellationDetails.from_result(result)
    print(f"Error: {cancellation.reason} — {cancellation.error_details}")

Converting text to natural-sounding audio

Python — Text-to-Speech with Neural Voice

import os
import azure.cognitiveservices.speech as speechsdk

speech_config = speechsdk.SpeechConfig(
    subscription = os.environ.get("SPEECH_KEY"),
    region       = os.environ.get("SPEECH_REGION")
)

# Set the voice to use for speech synthesis
# Voice name format: "Language-Region-VoiceName"
# Full list: https://learn.microsoft.com/azure/ai-services/speech-service/language-support
speech_config.speech_synthesis_voice_name = "en-US-AriaNeural"

# Configure audio OUTPUT — where to save or play the audio
# from_audio_file_output(): write to a .wav file
# For speakers: AudioOutputConfig(use_default_speaker=True)
audio_output = speechsdk.audio.AudioOutputConfig(
    filename = "output_speech.wav"
)

# SpeechSynthesizer combines config + audio output
synthesizer = speechsdk.SpeechSynthesizer(
    speech_config = speech_config,
    audio_config  = audio_output
)

# ── Option 1: Plain text synthesis ────────────────────────────────────
result = synthesizer.speak_text_async(
    "Hello! Welcome to the AI-102 study hub. Good luck on your exam!"
).get()  # .get() waits for the async operation to complete

if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
    print("Audio saved to output_speech.wav")


# ── Option 2: SSML for precise control ────────────────────────────────
# SSML (Speech Synthesis Markup Language) gives fine-grained control
# over how the text is spoken — rate, pitch, pauses, emphasis
ssml_text = """
<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="en-US">
    <voice name="en-US-AriaNeural">
        <prosody rate="slow" pitch="+5%">
            This announcement is very important.
        </prosody>
        <break time="500ms"/>
        Please listen carefully.
    </voice>
</speak>
"""
# speak_ssml_async() for SSML input instead of plain text
result_ssml = synthesizer.speak_ssml_async(ssml_text).get()

SSML elements — exam cheat sheet

SSML ElementWhat it doesExample
<voice>Selects the voice to use<voice name="en-US-GuyNeural">
<prosody>Controls rate, pitch, volume<prosody rate="slow" pitch="-10%">
<break>Inserts a pause<break time="1s"/>
<emphasis>Adds emphasis to words<emphasis level="strong">critical</emphasis>
<say-as>Controls how specific content is spoken<say-as interpret-as="date">2026-04-15</say-as>
<phoneme>Specifies exact pronunciation<phoneme alphabet="ipa" ph="ˈæzjʊr">Azure</phoneme>

Translating spoken audio in real time

Speech Translation converts spoken words from one language directly to text (or speech) in another language — in real time. It's different from using Translator on text — it handles the audio directly.

import os
import azure.cognitiveservices.speech as speechsdk

# SpeechTranslationConfig extends SpeechConfig with translation settings
translation_config = speechsdk.translation.SpeechTranslationConfig(
    subscription  = os.environ.get("SPEECH_KEY"),
    region        = os.environ.get("SPEECH_REGION"),
    speech_recognition_language = "en-US"   # The SPOKEN input language
)

# Add one or more target languages to translate INTO
# These are text output languages (ISO codes without region: "fr", "es", "de")
translation_config.add_target_language("fr")   # French
translation_config.add_target_language("es")   # Spanish

# Optional: set a voice for speech OUTPUT (translated audio)
# If set, the service also synthesises the translated text into audio
translation_config.voice_name = "fr-FR-DeniseNeural"

audio_config = speechsdk.AudioConfig(filename="english_speech.wav")

# TranslationRecognizer performs speech recognition + translation
translator = speechsdk.translation.TranslationRecognizer(
    translation_config = translation_config,
    audio_config       = audio_config
)

result = translator.recognize_once()

if result.reason == speechsdk.ResultReason.TranslatedSpeech:
    print(f"Original:  {result.text}")
    # result.translations is a dictionary: {"fr": "Bonjour...", "es": "Hola..."}
    for lang, translation in result.translations.items():
        print(f"  {lang.upper()}: {translation}")

Identifying who is speaking

Speaker VerificationSpeaker Identification
Question"Is this the person they claim to be?""Which of these enrolled people is speaking?"
InputAudio + claimed speaker IDAudio + list of enrolled speaker IDs
OutputAccept / Reject + confidenceBest matching speaker ID + confidence
Use caseVoice authentication ("my voice is my password")Meeting transcription with speaker attribution
EnrollmentUser records passphrase samplesEach speaker records audio samples
🎯
Exam Tip — Verification vs Identification

"A bank wants to verify that the caller is actually the account holder before giving account information."Speaker Verification (is this person who they say they are?)

"A company records team meetings and wants transcripts that show who said each sentence."Speaker Identification (which of our enrolled employees is speaking?)

Improving recognition for your domain

Standard speech-to-text models are trained on general language. If your application involves domain-specific terminology (medical, legal, technical), unusual proper nouns, strong accents, or noisy environments — a Custom Speech model significantly improves accuracy.

📝
Acoustic Data

Audio recordings + transcripts from your actual usage environment. Helps the model adapt to your recording conditions (room acoustics, microphone quality, noise levels).

📖
Language Data

Plain text samples of vocabulary, phrases, and sentences used in your domain. Teaches the model domain terminology, brand names, and jargon without needing audio recordings.

📚
Pronunciation Data

Phonetic pronunciations for words the standard model gets wrong — e.g. uncommon proper names, technical acronyms, or domain-specific abbreviations. Provides the correct phoneme sequences.

Custom Speech vs Standard Speech — when to use which

ScenarioUse StandardUse Custom
General conversation in a clear environment
Medical transcription with clinical terms
Call centre with background noise
Brand names / product names misrecognised
Strong regional accents
Meeting transcription in English

Choosing the right STT service

Both services transcribe speech to text — the exam tests when to use which.

NeedUse Azure AI SpeechUse Whisper (Azure OpenAI)
Real-time streaming transcription✓ — supports streaming✗ — file-based only
Custom vocabulary / domain terms✓ — Custom Speech model✗ — no custom training
Speaker identification✓ — built-in feature✗ — not supported
Text-to-speech needed too✓ — same SDK✗ — Whisper is STT only
Highest transcription accuracyGood✓ — generally higher accuracy
Already using Azure OpenAI✓ — simpler integration
Batch offline transcription✓ — Batch Transcription✓ — audio.transcriptions.create()

Speech Services — what the exam tests

⚠️
Top 5 Tested Facts

1. recognize_once() vs continuous — recognize_once() handles a single utterance and stops. For long audio (meetings, calls), use start_continuous_recognition() with event handlers.

2. result.reason == RecognizedSpeech — Always check result.reason before accessing result.text. ResultReason.NoMatch means audio detected but speech unclear. ResultReason.Canceled means an error occurred.

3. Speech Translation = audio in, text (or audio) out — Works directly on audio streams. Add target languages with add_target_language(). result.translations is a dictionary.

4. Speaker Verification = authentication, Speaker Identification = attribution — Know which scenario calls for which.

5. Custom Speech for domain vocabulary — When exam says "technical terms not recognised" or "brand names misidentified" → Custom Speech model with pronunciation data or language data.

Test your understanding

Topic 2 Quiz — Speech Services1 / 5
Scenario: A call centre records all customer service calls. The company wants to transcribe 10,000 hours of archived recordings overnight, with no real-time requirement — just accurate text output stored in Azure Blob Storage.

Which speech transcription approach is most appropriate?

💡 Explanation

B is correct. Batch Transcription is specifically designed for large-scale offline transcription of pre-recorded audio files stored in Azure Blob Storage. You submit a job, the service processes thousands of files concurrently, and results are written to output storage. It's significantly cheaper and more efficient than real-time recognition for archival processing. Using recognize_once() per file (A) would require sequential processing and is designed for real-time use. TTS (C) and Speech Translation (D) don't address transcription of existing recordings.

Scenario: A hospital wants to use speech recognition to transcribe doctor-patient consultations. Standard speech recognition struggles with drug names, medical abbreviations, and specialist terminology like "tachycardia", "myocardial infarction", and drug dosage instructions.

What should be implemented to improve recognition accuracy?

💡 Explanation

B is correct. Custom Speech models are specifically designed to improve recognition for domain-specific vocabulary. You train the model with medical language data (text samples of medical phrases, drug names, procedures) and pronunciation data (phonetic pronunciations of terms the standard model gets wrong). This directly addresses the problem. Subscription tier (A) doesn't affect vocabulary. Whisper (C) has no custom training capability and isn't specifically better at medical terms. NER post-processing (D) identifies what entities are in the text — it can't fix transcription errors from incorrect phoneme matching.

Scenario: A multinational company runs international conference calls in English. They want all participants to simultaneously receive translated captions in their own language — French participants see French, Spanish participants see Spanish — in real time as the English speaker talks.

Which Azure AI Speech feature handles this?

💡 Explanation

B is correct. Speech Translation directly translates spoken audio to multiple target languages in real time. Using add_target_language() for each target, the TranslationRecognizer produces result.translations as a dictionary with translations for all target languages simultaneously. While option A (STT + separate Translator call) is technically possible, it adds latency and complexity. Speech Translation is the purpose-built solution for real-time audio translation. Speaker Identification (C) identifies who is speaking, not language preferences. TTS (D) generates audio, not translations.

A fintech app allows customers to authenticate by speaking a passphrase into their phone. The system checks whether the voice matches the account holder's previously enrolled voice. Which Azure AI Speech feature is being used?

💡 Explanation

B is correct. Speaker Verification answers: "Is this person who they claim to be?" The customer claims to be Account Holder X, the system compares their voice to X's enrolled voice profile, and returns Accept/Reject + confidence score. This is authentication. Speaker Identification (A) answers "which of these people is speaking?" — used when you don't know who the speaker is and have a list of candidates. Custom Speech (D) improves STT vocabulary, not biometric authentication. Speech Translation (C) translates language, not authentication.

A developer uses SpeechConfig and a SpeechRecognizer but after calling recognize_once(), they get result.reason == ResultReason.NoMatch. What does this mean?

💡 Explanation

B is correct. ResultReason.NoMatch means audio was received and processed, but no recognisable speech could be extracted. Common causes: audio is too quiet, there's too much background noise, the language is different from what's configured in speech_recognition_language, or the audio contains non-speech sounds. Three important result reasons: RecognizedSpeech = success (read result.text), NoMatch = audio processed but no speech found, Canceled = error (check CancellationDetails for the error message — authentication failures show up here, not as NoMatch).

Mark this topic as complete