将快速听录 API 与 Azure 语音配合使用

快速听录 API 用于听录音频文件并同步返回结果,且速度比实时音频更快。 在您需要尽快获得音频录制的转录文本,并且延迟可预测的情况下,可以使用快速转录,例如:

  • 快速音频或视频听录、字幕和编辑。
  • 会议记录
  • 语音邮件

与批量听录 API 不同,快速听录 API 仅生成显示形式(而不是词法形式)的听录内容。 显示形式是一种更方便阅读的听录形式,包含标点和大写。

先决条件

  • 快速听录 API 可用的区域之一中的Azure语音资源。 有关受支持区域的当前列表,请参阅 语音服务区域表

  • 音频文件(长度小于 2 小时且大小小于 300 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"}"'

在以下部分中,内联音频上传用作示例。

使用快速转录 API

我们了解如何在以下场景中使用快速听录 API (通过 听录 - 转录):

  • 指定的已知区域设置: 使用已知的区域设置转录音频文件。 如果知道音频文件的地域设置,可以指定它以提高转录准确性并减少延迟。
  • 启用语言识别:转录含语言识别的音频文件。 如果不确定音频文件的区域设置,可以启用语言标识,让语音服务标识区域设置(每个音频一个区域设置)。
  • 多语言听录(预览版):使用最新的多语言语音听录模型转录音频文件。 如果音频包含要持续准确地听录的多语言内容,则可以在不指定区域设置代码的情况下使用最新的多语言语音听录模型。
  • 启用了分割聚类:转录启用了分割聚类功能的音频文件。 分割聚类可区分对话中的不同说话人。 语音服务提供有关哪个讲话者在转录语音的特定部分发言的信息。
  • 启用了多声道:转录包含一个或两个声道的音频文件。 多声道听录对于具有多个声道的音频文件非常有用,例如包含多个说话人的音频文件或有背景噪音的音频文件。 默认情况下,快速听录 API 将所有输入声道合并到单个声道,然后执行听录。 如果不希望这样处理,可以独立转录各个声道,而不进行合并。

使用音频文件和请求正文属性向transcriptions终结点发出多部分/表单数据 POST 请求。

以下示例演示了如何使用指定的区域设置转录音频文件。 如果知道音频文件的地域设置,可以指定它以提高转录准确性并减少延迟。

  • YourSpeechResourceKey 替换为语音资源密钥。
  • YourServiceRegion 替换为你的语音资源所在区域。
  • YourAudioFile替换为音频文件的路径。

重要

对于建议的无密码身份验证与 Microsoft Entra ID, 请将 --header 'Ocp-Apim-Subscription-Key: YourSpeechResourceKey' 替换为 --header "Authorization: Bearer YourAccessToken"。 有关无密钥身份验证的详细信息,请参阅 基于角色的访问控制 作指南。

curl --location 'https://YourServiceRegion.api.cognitive.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。 有关支持的语言环境的详细信息,请参阅 语音转文本支持的语言

有关快速听录 API locales 和其他属性的详细信息,请参阅本指南后面的“请求配置选项”部分。

响应包括 durationMillisecondsoffsetMilliseconds等。 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 错误代码(请求过多),请按照最佳做法在自动缩放期间缓解限制

请求配置选项

下面是一些属性选项,可用于在调用 Transcriptions - Transcribe 操作时配置转录。

资产 DESCRIPTION 必需还是可选
channels 要单独转录的声道的从零开始的索引列表。 除非启用分割聚类,否则最多支持两个声道。 默认情况下,快速听录 API 将所有输入声道合并到单个声道,然后执行听录。 如果不希望这样处理,可以独立转录各个声道,而不进行合并。

如果要从立体声音频文件中单独转录各个声道,需要指定 [0,1][0][1]。 否则,立体声音频将合并为单声道,并且仅转录单个声道。

如果音频是立体声且已启用分割聚类,则无法将 channels 属性设置为 [0,1]。 语音服务不支持对多个声道进行分割聚类。

对于单声道音频,系统将忽略 channels 属性,始终将音频作为单声道进行转录。
可选
diarization 分割聚类配置。 分割聚类是在一个音频声道中识别和分离说话人的过程。 例如,指定 "diarization": {"maxSpeakers": 2, "enabled": true}。 然后,听录文件会包含每个已转录短语的 speaker 个条目(例如 "speaker": 0"speaker": 1)。 可选
locales 语言列表应与要转录的音频数据的预期语言相匹配。

如果知道音频文件的地域设置,可以指定它以提高转录准确性并减少延迟。 如果指定了单个语言区域,将使用该语言区域进行转录。

但是,如果不确定区域,可以指定多个区域以进行语言识别。 候选语言列表越精确,语言识别可能越准确。

如果未指定任何语言区域,语音服务将使用最新的多语言模型来识别语言区域,自动进行转录。

可以通过转录 - 列出支持的语言区域 REST API(API 版本 2024-11-15 或更高版本)获取最新支持的语言。 有关区域设置的详细信息,请参阅“语音服务语言支持”文档
(可选)但如果你知道预期的区域设置,建议指定该区域设置。
phraseList 短语列表是提前提供的字词或短语列表,可帮助改进识别。 添加到短语列表的短语具有较高的重要性,从而更有可能被识别。 例如,指定 phraseList":{"phrases":["Contoso","Jessie","Rehaan"]}。 API 版本 2025-10-15 支持短语列表。 有关详细信息,请参阅 使用短语列表提高识别准确性 可选
profanityFilterMode 指定如何处理识别结果中的不雅内容。 接受的值为 None(禁用不雅内容筛选)、Masked(将不雅内容替换为星号)、Removed(从结果中删除所有不雅内容)或 Tags(添加不雅内容标记)。 默认值为 Masked 可选

Reference 文档 | Package (PyPi) | GitHub示例

先决条件

Microsoft Entra ID先决条件

若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,需要:

  • 安装用于无密钥身份验证的 Azure CLI 和 Microsoft Entra ID。
  • Cognitive Services User 角色分配给用户帐户。 可以在 Azure 门户中的 访问控制(IAM)>添加角色分配下分配角色。

Setup

  1. 使用以下命令创建一个名为 transcription-quickstart 的新文件夹,并转到快速入门文件夹:

    mkdir transcription-quickstart && cd transcription-quickstart
    
  2. 创建并激活虚拟Python环境以安装本教程所需的包。 建议在安装Python包时始终使用虚拟或 conda 环境。 否则,可以中断Python的全局安装。 如果已安装 Python 3.9 或更高版本,请使用以下命令创建虚拟环境:

    py -3 -m venv .venv
    .venv\Scripts\Activate.ps1
    

    激活Python环境时,从命令行运行 pythonpip 使用应用程序的 .venv 文件夹中的 Python 解释器。 使用 deactivate 命令退出Python虚拟环境。 稍后可以根据需要重新激活它。

  3. 创建名为 requirements.txt的文件。 将以下包添加到文件:

    azure-ai-transcription
    azure-identity
    
  4. 安装这些软件包:

    pip install -r requirements.txt
    

注释

对于Microsoft Entra ID身份验证(建议用于生产),请安装 azure-identity并配置身份验证,如Microsoft Entra ID先决条件部分所述。

Code

  1. 使用以下代码创建名为 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

  2. <path-to-your-audio-file.wav>替换为音频文件的路径。 该服务支持 WAV、MP3、FLAC、OGG 和其他常见音频格式。

  3. 运行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.

Reference 文档 | Package (Maven) | GitHub示例

先决条件

设置环境

  1. 创建一个名为transcription-quickstart的新文件夹并导航到它。

    mkdir transcription-quickstart && cd transcription-quickstart
    
  2. 在项目目录的根目录中,创建一个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-beta.2</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 结构。 此配置更改允许更简单的平面项目结构。

  3. 安装依赖项:

    mvn clean install
    

设置环境变量。

必须对应用程序进行身份验证才能访问语音服务。 SDK 支持 API 密钥和Microsoft Entra ID身份验证。 它根据设置的环境变量自动检测要使用的方法。

首先,设置语音资源的终结点。 将 <your-speech-endpoint> 替换为您的实际资源名称:

$env:AZURE_SPEECH_ENDPOINT="<your-speech-endpoint>"

然后,选择以下身份验证方法之一:

设置 API 密钥环境变量:

$env:AZURE_SPEECH_API_KEY="<your-speech-key>"

请不要设置 AZURE_SPEECH_API_KEY,而是配置以下凭据源之一:

  • Azure CLI:在开发计算机上运行 az login
  • Managed Identity:对于在Azure(应用服务、Azure Functions、VM)中运行的应用)。
  • 环境变量:设置 AZURE_TENANT_IDAZURE_CLIENT_IDAZURE_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

清理资源

完成快速入门后,可以删除项目文件夹:

rm -rf transcription-quickstart