快速轉錄 API 的用於轉錄音頻文件,並能同步且比實時更快地回傳結果。 在當您需要以可預測的延遲盡快獲得錄音文字記錄的情況下,使用快速轉錄,例如:
- 快速的音訊或影片轉錄、字幕與剪輯。
- 會議紀要
- 語音信箱
與批次轉錄 API 不同,快速轉錄 API 僅產生顯示形式(非詞彙形式)的轉錄。 顯示形式是較易讀的轉錄形式,包含標點符號與大小寫。
提示
你也可以使用最新的 LLM 驅動的語音轉錄與語音翻譯功能LLM 語音。
功能可用性
下表顯示快速轉錄 API 在使用與未使用 LLM Speech 的情況下,以及使用 MAI-Transcribe-2 時所支援的轉錄功能:
MAI-Transcribe-2 欄位僅顯示 MAI-Transcribe-2 的功能。 關於支援的型號版本及特定型號的設定選項,請參見Azure語音中的MAI-Transcribe。
| 特色 | 快速轉錄(預設) | LLM 演講(強化版) | MAI-轉錄-2 |
|---|---|---|---|
| 轉錄 | ✅ (語音模型轉錄) | ✅ (多模態模型) | ✅ (語音轉文字模型) |
| 翻譯 | ❌ | ✅ (多模態模型) | ❌ |
| 分段標記 | ✅ | ✅ | ✅ |
| 頻道(立體聲) | ✅ | ✅ | ❌ |
| 髒話過濾 | ✅ | ✅ | ✅ |
| 指定地點 | ✅ | ✅ | ✅ |
| 自訂提示 | ❌ | ✅ | ❌ |
| 短語列表 | ✅ | ✅ | ✅ |
| 區段層級時間戳記 | ✅ | ✅ | ✅ |
| 文字層級時間戳 | ✅ | ✅ | ✅ |
提示
關於選擇候選地點、使用多語言模型、啟用diarization,以及在回應中驗證 locale 和 speaker 的指引,請參見 「語音轉錄的語言識別與diarization配置」。
你可以在 Microsoft Foundry 嘗試快速轉錄,不需要寫任何程式碼。
先決條件
- 一個 Azure 訂閱。 免費創建一個。
- 一個鑄造廠的專案。 如果你需要建立專案,請參考 Create a Microsoft Foundry 專案。
試試快速轉錄
- 到 語音轉文字功能頁面 ,選擇 「在 Playground 開啟」。
- 在最上方下拉選單中,選擇 快速轉錄。
- 可選擇性地使用 參數 區塊來更改語言、髒話政策及其他設定。
- 請使用 上傳檔案 區段選擇你的音訊檔案。 然後選擇 開始。
- 請在 逐字稿 標籤中查看轉錄結果。可選擇性地在 JSON 標籤中查看原始 API 回應輸出。
- 切換到 程式碼 標籤,取得應用程式中使用快速轉錄的範例程式碼。
先決條件
這是 Azure 語音資源,位於快速轉錄 API 可用區域之一。 有關目前支援區域的清單,請參閱 語音服務區域表。
一個音訊檔案(長度少於 5 小時,大小少於 500 MB),採用批次轉錄 API 支援的格式與編解碼器之一:WAV、MP3、OPUS/OGG、FLAC、WMA、AAC、ALAW 在 WAV 容器、MULAW 在 WAV 容器、AMR、WebM 和 SPEEX。 欲了解更多支援的音訊格式資訊,請參閱支援的音訊格式。
上傳音訊
您可以以下方式提供音訊資料以快速轉錄:
- 線上音訊上傳
--form 'audio=@"YourAudioFile"'
- 來自公開網址的音訊
--form 'definition="{"audioUrl": "https://crbn.us/hello.wav"}"'
提示
對於較長的音訊檔案,建議從公開網址上傳。
以下章節以內嵌音訊上傳為例。
使用快速轉錄 API
提示
可以試試Microsoft Foundry 入口網站 快速轉錄。
我們學習如何使用快速轉錄 API(透過 Transcriptions - Transcribe)來處理以下情境:
- 指定已知地點:轉錄指定地點的音訊檔案。 如果你知道音訊檔案的所在地,可以指定以提升轉錄準確度並降低延遲。
- 語言識別已開啟:在語言識別開啟的狀態下轉錄音訊檔案。 如果你不確定音訊檔案的地點,可以開啟語言識別,讓語音服務辨識地點(每個音訊一個地點)。
- 多語言轉錄:使用最新的多語言語音轉錄模型轉錄音訊檔案。 如果你的音訊包含多語言內容,想要連續且準確地轉錄,你可以使用最新的多語言語音轉錄模型,而不必指定地區代碼。
- 語者辨識開啟:使用語者辨識功能轉錄音訊檔案。 說話者分離可區分交談中不同的說話者。 語音服務提供關於哪位講者在轉錄演講中特定部分發言的資訊。
- 多聲道已啟用:轉錄包含一或兩個聲道的音訊檔案。 多聲道轉錄對於多聲道的音訊檔案特別有用,例如多喇叭的音訊檔案或帶有背景噪音的音訊檔案。 預設情況下,快速轉錄 API 會將所有輸入通道合併為單一通道,然後執行轉錄。 如果這不理想,頻道可以獨立轉錄而不合併。
向 transcriptions 端點發送 multipart/form-data POST 請求,包含音訊檔案和請求主體屬性。
以下範例說明如何將指定地點的音訊檔案轉錄。 如果你知道音訊檔案的所在地,可以指定以提升轉錄準確度並降低延遲。
- 用你的語音資源金鑰替換
YourSpeechResourceKey。 - 用你的語音資源名稱替換
YourResourceName。 - 用你的音訊檔案路徑替換
YourAudioFile。
重要
對於 Microsoft Entra ID 建議的無金鑰驗證,請將 --header 'Ocp-Apim-Subscription-Key: YourSpeechResourceKey' 替換為 --header "Authorization: Bearer YourAccessToken"。 欲了解更多無金鑰認證的資訊,請參閱 基於角色的存取控制 操作指南。
curl --location 'https://YourResourceName.cognitiveservices.azure.com/speechtotext/transcriptions:transcribe?api-version=2025-10-15' \
--header 'Content-Type: multipart/form-data' \
--header 'Ocp-Apim-Subscription-Key: YourSpeechResourceKey' \
--form 'audio=@"YourAudioFile"' \
--form 'definition="{
"locales":["en-US"]}"'
依照以下指示建立表單定義:
- 設定可選(但建議)
locales屬性,該屬性應該與音訊資料預期轉錄地點相符。 在此範例中,位置設定為en-US。 欲了解更多支援地點的資訊,請參閱 語音轉文字支援語言。
欲了解更多關於 locales 快速轉錄 API 的其他特性,請參閱本指南後面的 請求設定選項 章節。
回應包括 durationMilliseconds、 offsetMilliseconds、 以及更多。 該 combinedPhrases 屬性包含所有講者的完整轉錄。
{
"durationMilliseconds": 182439,
"combinedPhrases": [
{
"text": "Good afternoon. This is Sam. Thank you for calling Contoso. How can I help? Hi there. My name is Mary. I'm currently living in Los Angeles, but I'm planning to move to Las Vegas. I would like to apply for a loan. Okay. I see you're currently living in California. Let me make sure I understand you correctly. Uh You'd like to apply for a loan even though you'll be moving soon. Is that right? Yes, exactly. So I'm planning to relocate soon, but I would like to apply for the loan first so that I can purchase a new home once I move there. And are you planning to sell your current home? Yes, I will be listing it on the market soon and hopefully it'll sell quickly. That's why I'm applying for a loan now, so that I can purchase a new house in Nevada and close on it quickly as well once my current home sells. I see. Would you mind holding for a moment while I take your information down? Yeah, no problem. Thank you for your help. Mm-hmm. Just one moment. All right. Thank you for your patience, ma'am. May I have your first and last name, please? Yes, my name is Mary Smith. Thank you, Ms. Smith. May I have your current address, please? Yes. So my address is 123 Main Street in Los Angeles, California, and the zip code is 90923. Sorry, that was a 90 what? 90923. 90923 on Main Street. Got it. Thank you. May I have your phone number as well, please? Uh Yes, my phone number is 504-529-2351 and then yeah. 2351. Got it. And do you have an e-mail address we I can associate with this application? uh Yes, so my e-mail address is mary.a.sm78@gmail.com. Mary.a, was that a S-N as in November or M as in Mike? M as in Mike. Mike78, got it. Thank you. Ms. Smith, do you currently have any other loans? Uh Yes, so I currently have two other loans through Contoso. So my first one is my car loan and then my other is my student loan. They total about 1400 per month combined and my interest rate is 8%. I see. And you're currently paying those loans off monthly, is that right? Yes, of course I do. OK, thank you. Here's what I suggest we do. Let me place you on a brief hold again so that I can talk with one of our loan officers and get this started for you immediately. In the meantime, it would be great if you could take a few minutes and complete the remainder of the secure application online at www.contosoloans.com. Yeah, that sounds good. I can go ahead and get started. Thank you for your help. Thank you."
}
],
"phrases": [
{
"offsetMilliseconds": 960,
"durationMilliseconds": 640,
"text": "Good afternoon.",
"words": [
{
"text": "Good",
"offsetMilliseconds": 960,
"durationMilliseconds": 240
},
{
"text": "afternoon.",
"offsetMilliseconds": 1200,
"durationMilliseconds": 400
}
],
"locale": "en-US",
"confidence": 0.93554276
},
{
"offsetMilliseconds": 1600,
"durationMilliseconds": 640,
"text": "This is Sam.",
"words": [
{
"text": "This",
"offsetMilliseconds": 1600,
"durationMilliseconds": 240
},
{
"text": "is",
"offsetMilliseconds": 1840,
"durationMilliseconds": 120
},
{
"text": "Sam.",
"offsetMilliseconds": 1960,
"durationMilliseconds": 280
}
],
"locale": "en-US",
"confidence": 0.93554276
},
{
"offsetMilliseconds": 2240,
"durationMilliseconds": 1040,
"text": "Thank you for calling Contoso.",
"words": [
{
"text": "Thank",
"offsetMilliseconds": 2240,
"durationMilliseconds": 200
},
{
"text": "you",
"offsetMilliseconds": 2440,
"durationMilliseconds": 80
},
{
"text": "for",
"offsetMilliseconds": 2520,
"durationMilliseconds": 120
},
{
"text": "calling",
"offsetMilliseconds": 2640,
"durationMilliseconds": 200
},
{
"text": "Contoso.",
"offsetMilliseconds": 2840,
"durationMilliseconds": 440
}
],
"locale": "en-US",
"confidence": 0.93554276
},
{
"offsetMilliseconds": 3280,
"durationMilliseconds": 640,
"text": "How can I help?",
"words": [
{
"text": "How",
"offsetMilliseconds": 3280,
"durationMilliseconds": 120
},
{
"text": "can",
"offsetMilliseconds": 3440,
"durationMilliseconds": 120
},
{
"text": "I",
"offsetMilliseconds": 3560,
"durationMilliseconds": 40
},
{
"text": "help?",
"offsetMilliseconds": 3600,
"durationMilliseconds": 320
}
],
"locale": "en-US",
"confidence": 0.93554276
},
{
"offsetMilliseconds": 5040,
"durationMilliseconds": 400,
"text": "Hi there.",
"words": [
{
"text": "Hi",
"offsetMilliseconds": 5040,
"durationMilliseconds": 240
},
{
"text": "there.",
"offsetMilliseconds": 5280,
"durationMilliseconds": 160
}
],
"locale": "en-US",
"confidence": 0.93554276
},
{
"offsetMilliseconds": 5440,
"durationMilliseconds": 800,
"text": "My name is Mary.",
"words": [
{
"text": "My",
"offsetMilliseconds": 5440,
"durationMilliseconds": 80
},
{
"text": "name",
"offsetMilliseconds": 5520,
"durationMilliseconds": 120
},
{
"text": "is",
"offsetMilliseconds": 5640,
"durationMilliseconds": 80
},
{
"text": "Mary.",
"offsetMilliseconds": 5720,
"durationMilliseconds": 520
}
],
"locale": "en-US",
"confidence": 0.93554276
},
// More transcription results...
// Redacted for brevity
{
"offsetMilliseconds": 180320,
"durationMilliseconds": 680,
"text": "Thank you for your help.",
"words": [
{
"text": "Thank",
"offsetMilliseconds": 180320,
"durationMilliseconds": 160
},
{
"text": "you",
"offsetMilliseconds": 180480,
"durationMilliseconds": 80
},
{
"text": "for",
"offsetMilliseconds": 180560,
"durationMilliseconds": 120
},
{
"text": "your",
"offsetMilliseconds": 180680,
"durationMilliseconds": 120
},
{
"text": "help.",
"offsetMilliseconds": 180800,
"durationMilliseconds": 200
}
],
"locale": "en-US",
"confidence": 0.92022026
},
{
"offsetMilliseconds": 181960,
"durationMilliseconds": 280,
"text": "Thank you.",
"words": [
{
"text": "Thank",
"offsetMilliseconds": 181960,
"durationMilliseconds": 200
},
{
"text": "you.",
"offsetMilliseconds": 182160,
"durationMilliseconds": 80
}
],
"locale": "en-US",
"confidence": 0.92022026
}
]
}
註
語音服務是一種彈性服務。 如果您收到 429 錯誤碼 (要求過多),請遵循緩解自動縮放時節流的最佳做法。
請求設定選項
以下是一些在呼叫 「轉錄 - 轉錄 」操作時設定轉錄的屬性選項。
| 財產 | 描述 | 必修或選修 |
|---|---|---|
channels |
要分開轉錄之聲道的從零開始的索引清單。 最多支援兩個聲道,除非啟用說話者分離。 預設情況下,快速轉錄 API 會將所有輸入通道合併為單一通道,然後執行轉錄。 如果這不理想,頻道可以獨立轉錄而不合併。 如果你想從立體聲音訊檔案中分別轉錄這些通道,你需要指定 [0,1]、 [0]、 或 [1]。 否則,立體聲音訊會合併成單聲道,並僅轉錄單一聲道。如果音訊是立體聲且啟用了 diarization,那你就不能把屬性設 channels 成 [0,1]。 語音服務不支援多個頻道的語者識別。對於單聲道音訊,這個 channels 特性會被忽略,音訊總是以單一聲道的形式轉錄。 |
可選 |
diarization |
說話者分離組態。 語者辨別是在一個音頻聲道中辨識並分離多個說話者的過程。 例如,指定 "diarization": {"maxSpeakers": 2, "enabled": true}。 接著轉錄檔案包含每個轉錄短語的條目 speaker(例如 "speaker": 0 或 "speaker": 1)。 |
可選 |
locales |
區域的清單應該與要轉錄之音訊資料預期的區域相符。 如果你知道音訊檔案的所在地,可以指定以提升轉錄準確度並降低延遲。 若指定單一地點,則該地點用於轉錄。 但如果你不確定地點,也可以指定多個地點來使用語言識別。 語言識別若有更精確的候選地點清單,可能會更準確。 如果你沒有指定任何地區,語音服務會使用最新的多語言模型來識別地點並持續轉錄。 你可以透過 Transcriptions - List Supported Locales 的 REST API(API 版本 2024-11-15 或更新)取得最新支援的語言。 欲了解更多地點資訊,請參閱 語音服務語言支援 文件。 |
這是可選的,但如果你知道預期的區域,建議這樣做。 |
phraseList |
片語清單是事先提供的字詞或片語清單,可協助改善其辨識。 將片語加入片語清單會提升其重要性,因此更容易被辨識。 例如,指定 phraseList":{"phrases":["Contoso","Jessie","Rehaan"]}。 片語清單自 API 版本 2025-10-15 起支援。 欲了解更多資訊,請參閱 「透過短語清單提升識別準確度」。 |
可選 |
profanityFilterMode |
說明如何處理識別結果中的髒話。 被接受的數值包括 None 停用髒話過濾、 Masked 將髒話替換為星號、 Removed 移除所有髒話,或 Tags 新增髒話標籤。 預設值為 Masked。 |
可選 |
參考文件 | Package (PyPi) | GitHub samples
先決條件
- 一個 Azure 訂閱。 免費創建一個。
- Python 3.9 或更新版本。 如果你還沒安裝合適的 Python 版本,可以依照 VS Code Python Tutorial 的說明,最簡單地在作業系統上安裝 Python。
- Microsoft Foundry 資源 在支援區域之一建立。 欲了解更多區域可用性資訊,請參閱 區域支援。
- 一個供轉錄的範例
.wav音訊檔案。
Microsoft Entra ID 先決條件
建議使用 Microsoft Entra ID 進行無鑰匙認證,您需要:
- 安裝用於透過 Microsoft Entra ID 進行無金鑰驗證的 Azure CLI。
- 將
Cognitive Services User角色指派到你的使用者帳號。 你可以在Azure入口網站的 存取控制(IAM)>新增角色分配下分配角色。
設定
建立一個名為
transcription-quickstart的新資料夾,然後使用以下指令移至 quickstart 資料夾:mkdir transcription-quickstart && cd transcription-quickstart建立並啟用一個虛擬的 Python 環境,安裝你本教學所需的套件。 我們建議你安裝 Python 套件時,始終使用虛擬環境或 conda 環境。 否則,你可能會破壞你的全域 Python 安裝。 如果你已經安裝了 Python 3.9 或更高版本,請使用以下指令建立虛擬環境:
當你啟用 Python 環境時,從命令列執行
python或pip,會使用應用程式中.venv資料夾中的 Python 直譯器。 使用deactivate指令退出 Python 虛擬環境。 你需要時可以再重新啟用。建立一個名為 requirements.txt的檔案。 將以下套件加入檔案中:
azure-ai-transcription azure-identity安裝套件:
pip install -r requirements.txt
擷取資源資訊
你需要取得資源端點和 API 金鑰進行認證。
登入 Foundry 入口網站。
從左側選單選擇 管理中心 。 在 「連結資源」中,選擇你的語音或多服務資源。
選擇 鍵與端點。
複製 端點 和 金鑰 值。 利用這些值來設定環境變數。
設定以下環境變數:
註
對於 Microsoft Entra ID 認證(建議用於生產環境),安裝 azure-identity,並依照 Microsoft Entra ID 前置條件 節的說明設定認證。
Code
建立一個以以下代碼命名
transcribe_audio_file.py的檔案:import os from azure.core.credentials import AzureKeyCredential from azure.ai.transcription import TranscriptionClient from azure.ai.transcription.models import TranscriptionContent, TranscriptionOptions # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] api_key = os.environ["AZURE_SPEECH_API_KEY"] # Create the transcription client client = TranscriptionClient(endpoint=endpoint, credential=AzureKeyCredential(api_key)) # Path to your audio file (replace with your own file path) audio_file_path = "<path-to-your-audio-file.wav>" # Open and read the audio file with open(audio_file_path, "rb") as audio_file: # Create transcription options options = TranscriptionOptions(locales=["en-US"]) # Specify the language # Create the request content request_content = TranscriptionContent(definition=options, audio=audio_file) # Transcribe the audio result = client.transcribe(request_content) # Print the transcription result print(f"Transcription: {result.combined_phrases[0].text}") # Print detailed phrase information if result.phrases: print("\nDetailed phrases:") for phrase in result.phrases: print( f" [{phrase.offset_milliseconds}ms - " f"{phrase.offset_milliseconds + phrase.duration_milliseconds}ms]: " f"{phrase.text}" )參考資料: TranscriptionClient | TranscriptionContent | TranscriptionOptions | AzureKeyCredential
用你的音訊檔案路徑替換
<path-to-your-audio-file.wav>。 該服務支援 WAV、MP3、FLAC、OGG 及其他常見音訊格式。執行 Python 腳本:
python transcribe_audio_file.py
產出
腳本會將轉錄結果列印到主控台:
Transcription: Hi there! This is a sample voice recording created for speech synthesis testing. The quick brown fox jumps over the lazy dog. Just a fun way to include every letter of the alphabet. Numbers, like 1, 2, 3, are spoken clearly. Let's see how well this voice captures tone, timing, and natural rhythm. This audio is provided by samplefiles.com.
Detailed phrases:
[40ms - 4880ms]: Hi there! This is a sample voice recording created for speech synthesis testing.
[5440ms - 8400ms]: The quick brown fox jumps over the lazy dog.
[9040ms - 12240ms]: Just a fun way to include every letter of the alphabet.
[12720ms - 16720ms]: Numbers, like 1, 2, 3, are spoken clearly.
[17200ms - 22000ms]: Let's see how well this voice captures tone, timing, and natural rhythm.
[22480ms - 25920ms]: This audio is provided by samplefiles.com.
請求設定選項
可自訂 TranscriptionOptions 轉錄行為。 以下章節說明每種支援的配置,並示範如何應用。
多語言偵測
將多個語言地區候選傳遞至locales,以實現跨語言的語言識別。 該服務會偵測所使用的語言,並為每個片語標註所偵測的地點。 完全省略 locales 讓服務自動偵測所有沒有候選語言清單的語言。
from azure.core.credentials import AzureKeyCredential
from azure.ai.transcription import TranscriptionClient
from azure.ai.transcription.models import TranscriptionContent, TranscriptionOptions
client = TranscriptionClient(
endpoint=endpoint, credential=AzureKeyCredential(api_key)
)
with open(audio_file_path, "rb") as audio_file:
# Provide candidate locales — the service selects the best match per phrase
options = TranscriptionOptions(locales=["en-US", "es-ES", "fr-FR", "de-DE"])
result = client.transcribe(TranscriptionContent(definition=options, audio=audio_file))
for phrase in result.phrases:
locale = phrase.locale if phrase.locale else "detected"
print(f"[{locale}] {phrase.text}")
參考資料: TranscriptionOptions
演講者自動分段標記
語者分離可偵測並標註單一音訊聲道中的不同說話者。 建立一個能容納最多預期數量(2–35)講者的 TranscriptionDiarizationOptions 物件,並將其傳遞給 TranscriptionOptions。 結果中的每個片語都包含一個 speaker 識別碼。
from azure.core.credentials import AzureKeyCredential
from azure.ai.transcription import TranscriptionClient
from azure.ai.transcription.models import (
TranscriptionContent,
TranscriptionOptions,
TranscriptionDiarizationOptions,
)
client = TranscriptionClient(
endpoint=endpoint, credential=AzureKeyCredential(api_key)
)
with open(audio_file_path, "rb") as audio_file:
diarization_options = TranscriptionDiarizationOptions(
max_speakers=5 # Hint for maximum number of speakers (2-35)
)
options = TranscriptionOptions(
locales=["en-US"], diarization_options=diarization_options
)
result = client.transcribe(TranscriptionContent(definition=options, audio=audio_file))
for phrase in result.phrases:
speaker = phrase.speaker if phrase.speaker is not None else "Unknown"
print(f"Speaker {speaker} [{phrase.offset_milliseconds}ms]: {phrase.text}")
註
分段識別僅支援單聲道音訊。 如果您的音訊是立體聲,啟用説話者分辨時,請勿將 channels 屬性設為 [0, 1]。
參考資料: TranscriptionDiarizationOptionsTranscriptionOptions
短語列表
片語清單能提升領域專有名詞、專有名詞及罕見詞彙的辨識準確度。 設 biasing_weight 於 0.0 和 2.0 之間,以控制片語被偏好的強弱(較高的值會增加偏向)。
from azure.core.credentials import AzureKeyCredential
from azure.ai.transcription import TranscriptionClient
from azure.ai.transcription.models import (
TranscriptionContent,
TranscriptionOptions,
PhraseListProperties,
)
client = TranscriptionClient(
endpoint=endpoint, credential=AzureKeyCredential(api_key)
)
with open(audio_file_path, "rb") as audio_file:
phrase_list = PhraseListProperties(
phrases=["Contoso", "Jessie", "Rehaan"],
biasing_weight=1.5, # Weight between 0.0 and 2.0
)
options = TranscriptionOptions(locales=["en-US"], phrase_list=phrase_list)
result = client.transcribe(TranscriptionContent(definition=options, audio=audio_file))
print(result.combined_phrases[0].text)
欲了解更多資訊,請參閱 「透過短語清單提升識別準確度」。
參考資料: PhraseListPropertiesTranscriptionOptions
髒話過濾
利用參數 profanity_filter_mode 控制轉錄輸出中的髒話出現方式。 以下模式可供選擇:
| 模式 | 行為 |
|---|---|
"None" |
髒話會保持不變地傳遞。 |
"Masked" |
髒話被星號取代(預設)。 |
"Removed" |
髒話完全從輸出中移除。 |
"Tags" |
髒話會被 <profanity> XML 標籤包裹起來。 |
from azure.core.credentials import AzureKeyCredential
from azure.ai.transcription import TranscriptionClient
from azure.ai.transcription.models import TranscriptionContent, TranscriptionOptions
client = TranscriptionClient(
endpoint=endpoint, credential=AzureKeyCredential(api_key)
)
with open(audio_file_path, "rb") as audio_file:
options = TranscriptionOptions(
locales=["en-US"],
profanity_filter_mode="Masked" # Options: "None", "Removed", "Masked", "Tags"
)
result = client.transcribe(TranscriptionContent(definition=options, audio=audio_file))
print(result.combined_phrases[0].text)
參考資料: TranscriptionOptions
參考文件 | Package (NuGet) | GitHub samples
先決條件
- 一個 Azure 訂閱。 免費創建一個。
- .NET 8.0 SDK 或更新版本。
- Microsoft Foundry 資源 在支援區域之一建立。 欲了解更多區域可用性資訊,請參閱 區域支援。
- 一個供轉錄的範例
.wav音訊檔案。
Microsoft Entra ID 先決條件
建議使用 Microsoft Entra ID 進行無鑰匙認證,您需要:
- 安裝用於透過 Microsoft Entra ID 進行無金鑰驗證的 Azure CLI。
- 用Azure CLI登入時,請輸入
az login。 - 將
Cognitive Services User角色指派到你的使用者帳號。 你可以在Azure入口網站的 存取控制(IAM)>新增角色分配下分配角色。
設立專案
使用 .NET CLI 建立新的主控台應用程式:
dotnet new console -n transcription-quickstart cd transcription-quickstart安裝所需的套件:
dotnet add package Azure.AI.Speech.Transcription dotnet add package Azure.Identity
擷取資源資訊
你需要取得你的資源端點進行認證。
登入 Foundry 入口網站。
從左側選單選擇 管理中心 。 在 「連結資源」中,選擇你的語音或多服務資源。
選擇 鍵與端點。
複製 Endpoint 值並設定為環境變數:
$env:AZURE_SPEECH_ENDPOINT="<your-speech-endpoint>"
轉錄音訊
將 Program.cs 的內容替換為以下代碼:
using System;
using System.ClientModel;
using System.Linq;
using System.Threading.Tasks;
using Azure.AI.Speech.Transcription;
using Azure.Identity;
Uri endpoint = new Uri(Environment.GetEnvironmentVariable("AZURE_SPEECH_ENDPOINT")
?? throw new InvalidOperationException("Set the AZURE_SPEECH_ENDPOINT environment variable."));
// Use DefaultAzureCredential for keyless authentication (recommended).
// To use an API key instead, replace with:
// ApiKeyCredential credential = new ApiKeyCredential("<your-api-key>");
var credential = new DefaultAzureCredential();
TranscriptionClient client = new TranscriptionClient(endpoint, credential);
string audioFilePath = "<path-to-your-audio-file.wav>";
using FileStream audioStream = File.OpenRead(audioFilePath);
TranscriptionOptions options = new TranscriptionOptions(audioStream);
ClientResult<TranscriptionResult> response = await client.TranscribeAsync(options);
var channelPhrases = response.Value.CombinedPhrases.First();
Console.WriteLine(channelPhrases.Text);
執行應用程式:
dotnet run
從你的音訊檔轉錄下來的文字會印到主控台。
存取字級詳細資料
若要存取時間戳記、信賴度分數,和個別單字,請迭代片語:
foreach (TranscribedPhrase phrase in response.Value.Phrases)
{
Console.WriteLine($"\nPhrase: {phrase.Text}");
Console.WriteLine($" Offset: {phrase.Offset} | Duration: {phrase.Duration}");
Console.WriteLine($" Confidence: {phrase.Confidence:F2}");
foreach (TranscribedWord word in phrase.Words)
{
Console.WriteLine(
$" Word: '{word.Text}' | " +
$"Confidence: {word.Confidence:F2} | " +
$"Offset: {word.Offset}");
}
}
參考資料: TranscribedPhraseTranscribedWord
使用分離識別語者
語者分離在多語者音訊中,能識別誰在說話。
TranscriptionOptions options = new TranscriptionOptions(audioStream)
{
DiarizationOptions = new TranscriptionDiarizationOptions
{
MaxSpeakers = 4
}
};
ClientResult<TranscriptionResult> response = await client.TranscribeAsync(options);
foreach (TranscribedPhrase phrase in response.Value.Phrases)
{
Console.WriteLine($"Speaker {phrase.Speaker}: {phrase.Text}");
}
參考文件 | Package (npm) | GitHub samples
先決條件
- 一個 Azure 訂閱。 免費創建一個。
- Node.js LTS。
- Microsoft Foundry 資源 在支援區域之一建立。 欲了解更多區域可用性資訊,請參閱 區域支援。
- 一個供轉錄的範例
.wav音訊檔案。
Microsoft Entra ID 先決條件
建議使用 Microsoft Entra ID 進行無鑰匙認證,您需要:
- 安裝用於透過 Microsoft Entra ID 進行無金鑰驗證的 Azure CLI。
- 用 Azure CLI 登入時,請執行
az login。 - 將
Cognitive Services User角色指派到你的使用者帳號。 你可以在Azure入口網站的 存取控制(IAM)>新增角色分配下分配角色。
設立專案
建立一個新資料夾並初始化一個 Node.js 專案:
mkdir transcription-quickstart cd transcription-quickstart npm init -y安裝所需的套件:
npm install @azure/ai-speech-transcription @azure/identity透過將模組類型
package.json加入你的專案,設定專案使用 ES 模組:npm pkg set type=module或者手動將
"type": "module"添加到你的package.json檔案中。 這是範例import程式碼中陳述句運作的必要條件。
擷取資源資訊
你需要取得你的資源端點進行認證。
登入 Foundry 入口網站。
從左側選單選擇 管理中心 。 在 「連結資源」中,選擇你的語音或多服務資源。
選擇 鍵與端點。
複製 Endpoint 值並設定為環境變數:
轉錄音訊
建立一個以以下代碼命名
transcribe-audio-file.js的檔案:import { readFileSync } from "node:fs"; import { DefaultAzureCredential } from "@azure/identity"; import { TranscriptionClient } from "@azure/ai-speech-transcription"; const endpoint = process.env.AZURE_SPEECH_ENDPOINT; if (!endpoint) { throw new Error("Set the AZURE_SPEECH_ENDPOINT environment variable."); } // Use DefaultAzureCredential for keyless authentication (recommended). const client = new TranscriptionClient(endpoint, new DefaultAzureCredential()); const audioFile = readFileSync("<path-to-your-audio-file.wav>"); const result = await client.transcribe(audioFile, { locales: ["en-US"], }); console.log("Transcription:", result.combinedPhrases[0]?.text ?? "No text");用你的音訊檔案路徑替換
<path-to-your-audio-file.wav>。執行應用程式:
node transcribe-audio-file.js
產出
應用程式會將轉錄後的文字列印到主控台:
Transcription: Hi there! This is a sample voice recording.
常見請求選項
使用分離識別語者
const result = await client.transcribe(audioFile, {
locales: ["en-US"],
diarizationOptions: {
maxSpeakers: 4,
},
});
for (const phrase of result.phrases) {
console.log(`Speaker ${phrase.speaker}: ${phrase.text}`);
}
參考資料: 轉錄日記化選項
設定髒話過濾
import {
KnownProfanityFilterModes,
} from "@azure/ai-speech-transcription";
const result = await client.transcribe(audioFile, {
locales: ["en-US"],
profanityFilterMode: KnownProfanityFilterModes.Masked,
});
參考資料: 已知的髒話過濾器模式
新增短語清單
使用片語清單來提升領域專有名詞、專有名詞和縮寫的辨識度:
const result = await client.transcribe(audioFile, {
locales: ["en-US"],
phraseList: {
phrases: ["Contoso", "Jessie", "Rehaan"],
},
});
console.log("Transcription:", result.combinedPhrases[0]?.text ?? "No text");
參考資料: PhraseListProperties
啟用多語言偵測
當您不確定使用的是哪種語言時,可以嘗試使用多個區域設定。 該服務會偵測語言並每句回傳地點:
const result = await client.transcribe(audioFile, {
locales: ["en-US", "es-ES"],
});
for (const phrase of result.phrases) {
console.log(`[${phrase.locale}] ${phrase.text}`);
}
參考資料: TranscribedPhrase
參考文件 | Package (Maven) | GitHub samples
先決條件
- 一個 Azure 訂閱。 免費創建一個。
- Java 開發套件(JDK)8 或更新版本。
- Apache Maven 用於依賴管理和建置專案。
- Microsoft Foundry 資源 位於支援區域之一。 欲了解更多區域可用性資訊,請參閱語音 服務支援區域。
- 一個供轉錄的範例
.wav音訊檔案。
設定環境
建立一個名為
transcription-quickstart的新資料夾並進入:mkdir transcription-quickstart && cd transcription-quickstart在專案目錄根目錄建立
pom.xml一個包含以下內容的檔案:<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>transcription-quickstart</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>Speech Transcription Quickstart</name> <description>Quickstart sample for Azure Speech Transcription client library.</description> <url>https://github.com/Azure/azure-sdk-for-java</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.azure</groupId> <artifactId>azure-ai-speech-transcription</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.18.1</version> </dependency> </dependencies> <build> <sourceDirectory>.</sourceDirectory> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.1.0</version> <configuration> <mainClass>TranscriptionQuickstart</mainClass> </configuration> </plugin> </plugins> </build> </project>註
<sourceDirectory>.</sourceDirectory>設定會告訴 Maven 在目前目錄中尋找Java原始碼檔案,而非預設的src/main/java結構。 這種配置變更使專案結構更簡單。安裝相依性:
mvn clean install
設定環境變數
你的應用程式必須經過驗證才能存取語音服務。 SDK 支援 API 金鑰與 Microsoft Entra ID 認證。 它會根據你設定的環境變數自動偵測該用哪種方法。
首先,設定語音資源的端點。 請用你的實際資源名稱替換 <your-speech-endpoint> :
接著,選擇以下一種認證方法:
選項一:API 金鑰驗證(建議初學者)
設定 API 金鑰環境變數:
選項 2:Microsoft Entra ID 認證(建議用於生產環境)
與其設定 AZURE_SPEECH_API_KEY,不如設定以下其中一個憑證來源:
-
Azure CLI:在你的開發機上執行
az login。 - Managed Identity:用於Azure中運行的應用程式(App Service、Azure Functions、虛擬機)。
-
環境變數:設定
AZURE_TENANT_ID、AZURE_CLIENT_ID、AZURE_CLIENT_SECRET。 - Visual Studio Code 或 IntelliJ:透過你的 IDE 登入。
你還需要為你的身份指派認知 服務使用者 角色:
az role assignment create --assignee <your-identity> \
--role "Cognitive Services User" \
--scope /subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.CognitiveServices/accounts/<speech-resource-name>
註
在 Windows 設定環境變數後,重新啟動所有需要讀取變數的執行程式,包括主控台視窗。 在 Linux 或 macOS 上,執行 source ~/.bashrc (或你等效的 shell 設定檔)來讓變更生效。
建立應用程式
請在你的專案目錄中建立一個檔案, TranscriptionQuickstart.java 並使用以下程式碼:
import com.azure.ai.speech.transcription.TranscriptionClient;
import com.azure.ai.speech.transcription.TranscriptionClientBuilder;
import com.azure.ai.speech.transcription.models.AudioFileDetails;
import com.azure.ai.speech.transcription.models.TranscriptionOptions;
import com.azure.ai.speech.transcription.models.TranscriptionResult;
import com.azure.core.credential.KeyCredential;
import com.azure.core.util.BinaryData;
import com.azure.identity.DefaultAzureCredentialBuilder;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class TranscriptionQuickstart {
public static void main(String[] args) {
try {
// Get credentials from environment variables
String endpoint = System.getenv("AZURE_SPEECH_ENDPOINT");
String apiKey = System.getenv("AZURE_SPEECH_API_KEY");
// Create client with API key or Entra ID authentication
TranscriptionClientBuilder builder = new TranscriptionClientBuilder()
.endpoint(endpoint);
TranscriptionClient client;
if (apiKey != null && !apiKey.isEmpty()) {
// Use API key authentication
client = builder.credential(new KeyCredential(apiKey)).buildClient();
} else {
// Use Entra ID authentication
client = builder.credential(new DefaultAzureCredentialBuilder().build()).buildClient();
}
// Load audio file
String audioFilePath = "<path-to-your-audio-file.wav>";
byte[] audioData = Files.readAllBytes(Paths.get(audioFilePath));
// Create audio file details
AudioFileDetails audioFileDetails = new AudioFileDetails(BinaryData.fromBytes(audioData));
// Transcribe
TranscriptionOptions options = new TranscriptionOptions(audioFileDetails);
TranscriptionResult result = client.transcribe(options);
// Print result
System.out.println("Transcription:");
result.getCombinedPhrases().forEach(phrase ->
System.out.println(phrase.getText())
);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
用你的音訊檔案路徑替換 <path-to-your-audio-file.wav> 。
執行應用程式
使用 Maven 執行應用程式:
mvn compile exec:java
請求設定選項
可自訂 TranscriptionOptions 轉錄行為。 以下章節說明每種支援的配置,並示範如何應用。
多語言偵測
當你不指定地點時,服務會自動偵測並轉錄音訊中所有語言。 每個回傳的片語都包含一個 locale 欄位來識別偵測到的語言。
// No locale specified — service auto-detects all languages in the audio
TranscriptionOptions options = new TranscriptionOptions(audioFileDetails);
TranscriptionResult result = client.transcribe(options);
// Each phrase reports the detected locale
result.getPhrases().forEach(phrase ->
System.out.println(phrase.getLocale() + ": " + phrase.getText())
);
註
若未指定地點, locale 個別片語的欄位可能不一定能準確反映該片語的精確語言。
為了達到最高準確度,當您知道預期的區域時,請指定它。
參考資料: TranscriptionOptionsTranscribedPhrase.getLocale()
演講者自動分段標記
語者分離可偵測並標註單一音訊聲道中的不同說話者。 用 TranscriptionDiarizationOptions 來啟用並設定最大預期講者數量(2–35)。 結果中的每個片語都包含一個 speaker 識別碼。
import com.azure.ai.speech.transcription.models.TranscriptionDiarizationOptions;
// Configure diarization with a maximum of 5 speakers
TranscriptionDiarizationOptions diarizationOptions =
new TranscriptionDiarizationOptions()
.setMaxSpeakers(5);
TranscriptionOptions options = new TranscriptionOptions(audioFileDetails)
.setDiarizationOptions(diarizationOptions);
TranscriptionResult result = client.transcribe(options);
// Each phrase includes the detected speaker ID
result.getPhrases().forEach(phrase ->
System.out.println(
"[Speaker " + phrase.getSpeaker() + "] " + phrase.getText()
)
);
註
分段識別僅支援單聲道音訊。 如果您的音訊是立體聲,啟用説話者分辨時,請勿將 channels 屬性設為 [0,1]。
參考資料: TranscriptionDiarizationOptions, TranscriptionOptions.setDiarizationOptions(), TranscribedPhrase.getSpeaker()
短語列表
片語清單能提升領域專有名詞、專有名詞及罕見詞彙的辨識準確度。 你新增的片語會被識別器加權,因此更容易被正確轉錄。
import com.azure.ai.speech.transcription.models.PhraseListOptions;
import java.util.Arrays;
// Add terms that appear in your audio to improve recognition
PhraseListOptions phraseListOptions = new PhraseListOptions()
.setPhrases(Arrays.asList("Contoso", "Jessie", "Rehaan"));
TranscriptionOptions options = new TranscriptionOptions(audioFileDetails)
.setPhraseListOptions(phraseListOptions);
TranscriptionResult result = client.transcribe(options);
result.getCombinedPhrases().forEach(phrase ->
System.out.println(phrase.getText())
);
欲了解更多資訊,請參閱 「透過短語清單提升識別準確度」。
參考資料: PhraseListOptionsTranscriptionOptions.setPhraseListOptions()
髒話過濾
使用 ProfanityFilterMode 控制髒話在轉錄輸出中的顯示方式。 以下模式可供選擇:
| 模式 | 行為 |
|---|---|
NONE |
髒話會保持不變地傳遞。 |
MASKED |
髒話被星號取代(預設)。 |
REMOVED |
髒話完全從輸出中移除。 |
TAGS |
髒話會被 XML 標籤包裹起來。 |
import com.azure.ai.speech.transcription.models.ProfanityFilterMode;
TranscriptionOptions options = new TranscriptionOptions(audioFileDetails)
.setProfanityFilterMode(ProfanityFilterMode.MASKED);
TranscriptionResult result = client.transcribe(options);
System.out.println(result.getCombinedPhrases().get(0).getText());
參考資料: ProfanityFilterModeTranscriptionOptions.setProfanityFilterMode()
清理資源
完成快速啟動後,你可以刪除專案資料夾:
rm -rf transcription-quickstart
轉錄錯誤處理
當你呼叫快速轉錄 API 時,請實作重試邏輯來處理暫時錯誤和速率限制。 API 會強制執行速率限制,這在高並發操作時可能導致錯誤。
推薦重試配置
在短暫錯誤時最多重試五次。
使用指數後退:2秒、4秒、8秒、16秒、32秒。
總後退時間:62秒。
此設定可在速率限制的時間窗口內提供 API 足夠的恢復時間,特別是在使用多個並行工作者執行批次作業時。
何時使用重試邏輯
對以下錯誤類別實作重試邏輯:
HTTP 錯誤 - 重試條件:
- HTTP 429(速率限制)
- HTTP 500、502、503、504(伺服器錯誤)
-
status_code=None(不完整回應下載)
Azure SDK 網路錯誤 - 重試於:
ServiceRequestErrorServiceResponseError
這些錯誤將會包裹低階網路例外,如
urllib3.exceptions.ReadTimeoutError、連線重置和 TLS 失敗。Python 網路例外 - 重新嘗試於:
ConnectionErrorTimeoutErrorOSError
請勿重試以下錯誤,因為它們顯示客戶端問題需要修正:
- HTTP 400(錯誤請求)
- HTTP 401(未授權)
- HTTP 422(無法處理的實體)
- 其他用戶端錯誤(4xx 狀態碼)
實作說明
在每次重試前重設音訊檔案串流 (
seek(0))。當您使用並行工作者時,當面臨嚴格的速率限制情況時,預設的 HTTP 讀取超時(300 秒)可能會被超過。
該 API 可能會接受要求,但在產生回應時發生逾時。 此狀況可能以 SDK 包裝的網路錯誤形式出現,而非標準的 HTTP 錯誤。