Nota
O acesso a esta página requer autorização. Pode tentar iniciar sessão ou alterar os diretórios.
O acesso a esta página requer autorização. Pode tentar alterar os diretórios.
快速听录 API 用于同步和更快地听录音频文件,其返回结果速度比实时快。 在您需要尽快获得音频录制的转录文本,并且延迟可预测的情况下,可以使用快速转录,例如:
- 快速音频或视频听录、字幕和编辑。
- 会议笔记
- 语音邮件
与批量转录 API 不同,快速转录 API 仅以显示形式(而不是词法形式)生成转录。 显示形式是一种更具人类可读的听录形式,包括标点和大写。
Tip
有关如何选择候选区域设置、使用多语言模型、启用说话人分离,以及验证响应中的 locale 和 speaker 的指导,请参阅 配置语音转录的语言识别和说话人分离。
Prerequisites
快速听录 API 可用的某个区域中的 Azure 语音资源。 有关受支持区域的当前列表,请参阅 语音服务区域表。
音频文件(长度少于 5 小时且大小小于 500 MB),采用批处理听录 API 支持的格式和编解码器之一:WAV、MP3、OPUS/OGG、FLAC、WMA、AAC、WAV 容器中的 ALAW、WAV 容器中的 MULAW、AMR、WebM 和 SPEEX。 有关支持的音频格式的详细信息,请参阅 支持的音频格式。
上传音频
您可以通过以下方式提供音频数据以实现快速转录:
- 嵌入式音频上传
--form 'audio=@"YourAudioFile"'
- 来自公共 URL 的音频
--form 'definition="{"audioUrl": "https://crbn.us/hello.wav"}"'
Tip
对于长音频文件,建议从公共 URL 上传。
在以下部分中,内联音频上传用作示例。
使用快速转录API
我们了解如何在以下场景中使用快速听录 API (通过 听录 - 转录):
- 指定的已知区域设置:使用指定的区域设置转录音频文件。 如果知道音频文件的区域设置,可以指定它以提高听录准确性并最大程度地减少延迟。
- 语言识别:使用语言识别来转录音频文件。 如果不确定音频文件的区域设置,可以启用语言标识,让语音服务标识区域设置(每个音频一个区域设置)。
- 多语言听录:使用最新的多语言语音听录模型转录音频文件。 如果音频包含要持续准确地听录的多语言内容,则可以在不指定区域设置代码的情况下使用最新的多语言语音听录模型。
- 对音频文件进行分割:对音频文件进行分割。 分割聚类可区分对话中的不同说话人。 语音服务提供关于哪个说话人讲述了转录语音中特定部分的信息。
- 多通道启用:转录含一个或两个通道的音频文件。 多声道听录对于具有多个声道的音频文件非常有用,例如包含多个说话人的音频文件或有背景噪音的音频文件。 默认情况下,快速听录 API 将所有输入通道合并到单个通道,然后执行听录。 如果不理想,每个通道都可独立转录,不需要合并。
使用音频文件和请求正文属性向transcriptions终结点发出多部分/表单数据 POST 请求。
以下示例演示如何使用指定的区域设置转录音频文件。 如果知道音频文件的区域设置,可以指定它以提高听录准确性并最大程度地减少延迟。
- 将
YourSpeechResourceKey替换为语音资源密钥。 - 将
YourResourceName替换为你的语音资源名称。 - 将
YourAudioFile替换为音频文件的路径。
Important
对于建议使用 Microsoft Entra ID 的无密钥身份验证,请将 --header 'Ocp-Apim-Subscription-Key: YourSpeechResourceKey' 替换为 --header "Authorization: Bearer YourAccessToken"。 有关无密钥身份验证的详细信息,请参阅 基于角色的访问控制 操作指南。
curl --location 'https://YourResourceName.cognitiveservices.azure.cn/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
}
]
}
Note
语音服务是一项弹性服务。 如果收到 429 错误代码(请求过多),请按照 在自动缩放期间采用最佳做法来缓解限流问题。
请求配置选项
在调用 转录 - 转录 操作时,以下是一些用于配置转录的属性选项。
| 财产 | 说明 | 必需或可选 |
|---|---|---|
channels |
要单独转录的声道的从零开始的索引列表。 除非启用分割聚类,否则最多支持两个声道。 默认情况下,快速听录 API 将所有输入通道合并到单个通道,然后执行听录。 如果不理想,每个通道都可独立转录,不需要合并。 如果要单独从立体声音频文件中转录声道,则需要指定 [0,1]、[0]或[1]。 否则,立体声音频将合并为单声道,并且仅转录单个通道。如果音频是立体声且已启用分割,则无法将 channels 属性设置为 [0,1]。 语音服务不支持对多个通道进行分割。对于单声道音频,系统将忽略 channels 属性,始终将音频作为单声道进行转录。 |
Optional |
diarization |
分割聚类配置。 分割是在一个音频通道中识别和分离多个扬声器的过程。 例如,指定 "diarization": {"maxSpeakers": 2, "enabled": true}。 然后,转录文件中包含每个已转录短语的条目(如 speaker、"speaker": 0 或 "speaker": 1)。 |
Optional |
locales |
区域设置列表应与要转录的音频数据的预期区域设置匹配。 如果知道音频文件的区域设置,可以指定它以提高听录准确性并最大程度地减少延迟。 如果指定了单个语言区域,将使用该语言区域进行转录。 但是,如果不确定区域,可以指定多个区域以进行语言识别。 候选语言列表越精确,语言识别可能越准确。 如果未指定任何语言区域,语音服务将使用最新的多语言模型来识别语言区域,自动进行转录。 可以通过转录 - 列出受支持的语言区域 REST API(API 版本 2024-11-15 或更高版本)获取最新支持的语言。 有关区域设置的详细信息,请参阅“语音服务语言支持”文档。 |
(可选择执行,但如果你知道预期的区域语言环境,建议执行此操作。) |
phraseList |
短语列表是预先提供的单词或短语列表,可帮助改进其识别能力。 将短语添加到短语列表会增加其重要性,从而使它更有可能被识别。 例如,指定 phraseList":{"phrases":["Contoso","Jessie","Rehaan"]}。 API 版本 2025-10-15 支持短语列表。 有关详细信息,请参阅 使用短语列表提高识别准确性。 |
Optional |
profanityFilterMode |
指定如何处理识别结果中的不雅内容。 接受的值是 None 禁用不雅内容筛选、 Masked 用星号替换不雅内容、 Removed 删除结果中的所有不雅内容或 Tags 添加不雅内容标记。 默认值为 Masked。 |
Optional |
Reference 文档 | Package (PyPi) | GitHub示例
Prerequisites
- 一份 Azure 订阅。 创建一个试用帐户。
- Python 3.9 或更高版本。 如果未安装合适的 Python 版本,则可以按照 VS Code Python 教程中的说明操作,这是在操作系统上安装 Python 的最简单方法。
- 在一个受支持的区域中创建的 AI 服务资源 。 有关区域可用性的详细信息,请参阅 区域支持。
- 要转录的示例
.wav音频文件。
Microsoft Entra ID先决条件
若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:
- 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI。
- 将
Cognitive Services User角色分配给用户帐户。 可以在 Azure 门户中的 访问控制(IAM)>添加角色分配下分配角色。
Setup
使用以下命令创建一个名为
transcription-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
Note
对于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
Output
该脚本将听录结果输出到控制台:
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}")
扬声器分割
Diarization 检测并标记单个音频通道中的不同扬声器。 创建一个具有最大预期说话人数(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}")
Note
仅在单声道(mono)音频上支持语音分离。 如果音频是立体声,请不要在启用分割时将 channels 属性 [0, 1] 设置为。
参考:TranscriptionDiarizationOptions、TranscriptionOptions
短语列表
短语列表可提升域特定术语、正确名词和不常见字词的识别准确性。 设置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)
有关详细信息,请参阅 使用短语列表提高识别准确性。
参考:PhraseListProperties、TranscriptionOptions
不雅内容筛选
使用 profanity_filter_mode 参数控制不雅内容在听录输出中的显示方式。 以下模式可用:
| 模式 | Behavior |
|---|---|
"None" |
脏话会原样通过。 |
"Masked" |
不雅内容将替换为星号(默认值)。 |
"Removed" |
完全从输出中删除不雅内容。 |
"Tags" |
不雅内容被包含在 XML 标记 <profanity> 中。 |
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)
Prerequisites
- 一份 Azure 订阅。 创建一个试用帐户。
- .NET 8.0 SDK 或更高版本。
- 在一个受支持的区域中创建的 Azure AI 服务资源 。 有关区域可用性的详细信息,请参阅 区域支持。
- 要转录的示例
.wav音频文件。
Microsoft Entra ID先决条件
若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:
- 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI。
- 通过运行
az login,使用Azure CLI登录。 - 将
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
转录音频
将 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}");
}
}
参考:TranscribedPhrase、TranscribedWord
通过分割聚类确定说话人
说话人辨识可以识别在多说话者音频中谁在何时说话。
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示例
Prerequisites
- 一份 Azure 订阅。 创建一个试用帐户。
- Node.js LTS。
- 在一个受支持的区域中创建的 AI 服务资源 。 有关区域可用性的详细信息,请参阅 区域支持。
- 要转录的示例
.wav音频文件。
Microsoft Entra ID先决条件
若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:
- 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI。
- 通过运行
az login,使用 Azure CLI 登录。 - 将
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语句正常工作是必需的。
检索资源信息
您需要检索资源终结点以进行身份验证。
登录到 Azure 门户。
从语音或多服务资源的左侧菜单中选择 “密钥和终结点 ”。
复制 终结点 值并将其设置为环境变量:
转录音频
使用以下代码创建名为
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
Output
应用将转录的文本打印到控制台:
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}`);
}
参考:TranscriptionDiarizationOptions
设置不雅内容筛选
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");
启用多语言检测
如果你不确定所说的语言是哪一种,可传递多个语言区域选项。 服务会检测语言并为每个短语返回相应的区域设置:
const result = await client.transcribe(audioFile, {
locales: ["en-US", "es-ES"],
});
for (const phrase of result.phrases) {
console.log(`[${phrase.locale}] ${phrase.text}`);
}
参考文档 | Package (Maven) | GitHub 示例
Prerequisites
- 一份 Azure 订阅。 创建一个试用帐户。
- Java 开发工具包 (JDK) 8 或更高版本。
- Apache Maven 用于依赖项管理和生成项目。
- 其中一个受支持区域的 AI 服务资源 。 有关区域可用性的详细信息,请参阅 语音服务支持的区域。
- 要转录的示例
.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>Note
该
<sourceDirectory>.</sourceDirectory>配置告知 Maven 在当前目录中查找 Java 源文件,而不是默认src/main/java结构。 此配置更改允许更简单的平面项目结构。安装依赖项:
mvn clean install
设置环境变量。
必须对应用程序进行身份验证才能访问语音服务。 SDK 支持 API 密钥和Microsoft Entra ID 身份验证。 它根据设置的环境变量自动检测要使用的方法。
首先,设置语音资源的终结点。 用你的实际资源名称替换 <your-speech-endpoint>。
然后,选择以下身份验证方法之一:
选项 1:API 密钥身份验证(建议入门)
设置 API 密钥环境变量:
选项 2:Microsoft Entra ID身份验证(建议用于生产)
与其设置 AZURE_SPEECH_API_KEY,不如配置以下其中一个凭据来源:
-
Azure CLI:在开发计算机上运行
az login。 - 托管标识:适用于在 Azure 中运行的应用(应用服务、Azure Functions、VM)。
-
环境变量:设置
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>
Note
在 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())
);
Note
如果未指定区域设置,则各个短语上的 locale 字段可能并不总是准确反映该短语的语言。
为获得最高准确度,请在知道时指定预期的区域设置。
参考:TranscriptionOptions、TranscribedPhrase.getLocale()
扬声器分割
Diarization 检测并标记单个音频通道中的不同扬声器。 使用 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()
)
);
Note
仅在单声道(mono)音频上支持语音分离。 如果音频是立体声,请不要在启用分割时将 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())
);
有关详细信息,请参阅 使用短语列表提高识别准确性。
参考:PhraseListOptions、TranscriptionOptions.setPhraseListOptions()
不雅内容筛选
控制不雅语言在转录输出中的显示方式,使用ProfanityFilterMode。 以下模式可用:
| 模式 | Behavior |
|---|---|
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());
参考:ProfanityFilterMode、TranscriptionOptions.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 错误。