快速入门:识别语音并将其转换为文本

参考文档 | 包 (NuGet) | GitHub 上的其他示例

在本快速入门中,你将创建并运行应用程序以实时识别语音并将其转录为文本。

提示

可以在 Speech Studio 中试用实时语音转文本,且无需注册或编写任何代码。

若要改为异步听录音频文件,请参阅什么是批量听录。 如果不确定哪种语音转文本解决方案适合自己,请参阅什么是语音转文本?

先决条件

设置环境

语音 SDK 以 NuGet 包的形式提供并实现了 .NET Standard 2.0。 在本指南稍后部分安装语音 SDK。 有关任何其他要求,请参阅安装语音 SDK

设置环境变量。

必须对应用程序进行身份验证才能访问 Azure AI 服务资源。 对于生产,请使用安全的方式存储和访问凭据。 例如,获取语音资源的密钥后,请将其写入运行应用程序的本地计算机上的新环境变量。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性

若要为语音资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  • 要设置 SPEECH_KEY 环境变量,请将“your-key”替换为你的资源的某一个密钥。
  • 要设置 SPEECH_REGION 环境变量,请将 “your-region”替换为你的资源的某一个地区。
setx SPEECH_KEY your-key
setx SPEECH_REGION your-region

注意

如果你只需要访问当前控制台中的环境变量,可使用 set(而不是 setx)来设置环境变量。

添加环境变量后,你可能需要重启任何需要读取环境变量的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

识别来自麦克风的语音

按照以下步骤创建控制台应用程序并安装语音 SDK。

  1. 在需要新项目的位置打开命令提示符。 使用 .NET CLI 创建控制台应用程序,这将在项目目录中创建 Program.cs 文件。

    dotnet new console
    
  2. 使用 .NET CLI 在新项目中安装语音 SDK。

    dotnet add package Microsoft.CognitiveServices.Speech
    
  3. 将 Program.cs 的内容替换为以下代码:

    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.CognitiveServices.Speech;
    using Microsoft.CognitiveServices.Speech.Audio;
    
    class Program 
    {
        // This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
        static string speechKey = Environment.GetEnvironmentVariable("SPEECH_KEY");
        static string speechRegion = Environment.GetEnvironmentVariable("SPEECH_REGION");
    
        static void OutputSpeechRecognitionResult(SpeechRecognitionResult speechRecognitionResult)
        {
            switch (speechRecognitionResult.Reason)
            {
                case ResultReason.RecognizedSpeech:
                    Console.WriteLine($"RECOGNIZED: Text={speechRecognitionResult.Text}");
                    break;
                case ResultReason.NoMatch:
                    Console.WriteLine($"NOMATCH: Speech could not be recognized.");
                    break;
                case ResultReason.Canceled:
                    var cancellation = CancellationDetails.FromResult(speechRecognitionResult);
                    Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");
    
                    if (cancellation.Reason == CancellationReason.Error)
                    {
                        Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                        Console.WriteLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}");
                        Console.WriteLine($"CANCELED: Did you set the speech resource key and region values?");
                    }
                    break;
            }
        }
    
        async static Task Main(string[] args)
        {
            var speechConfig = SpeechConfig.FromSubscription(speechKey, speechRegion);        
            speechConfig.SpeechRecognitionLanguage = "en-US";
    
            using var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
            using var speechRecognizer = new SpeechRecognizer(speechConfig, audioConfig);
    
            Console.WriteLine("Speak into your microphone.");
            var speechRecognitionResult = await speechRecognizer.RecognizeOnceAsync();
            OutputSpeechRecognitionResult(speechRecognitionResult);
        }
    }
    
  4. 若要更改语音识别语言,请将 en-US 替换为其他支持的语言。 例如,使用 es-ES 表示西班牙语(西班牙)。 如果未指定语言,则默认值为 en-US。 若要详细了解如何识别可能说出的多种语言之一,请参阅语言识别

  5. 运行新的控制台应用程序,从麦克风开始进行语音识别:

    dotnet run
    

    重要

    确保按照设置环境变量所述设置 SPEECH_KEYSPEECH_REGION 环境变量。 如果未设置这些变量,示例会失败并显示错误消息。

  6. 当系统提示时,对着麦克风说话。 你说出的内容应该会显示为文本:

    Speak into your microphone.
    RECOGNIZED: Text=I'm excited to try speech to text.
    

备注

下面是其他一些注意事项:

  • 此示例使用 RecognizeOnceAsync 操作听录 30 秒以内的语音,或直到检测到静音。 如要详细了解长音频的持续识别(包括多语言对话),请参阅如何识别语音

  • 若要识别音频文件中的语音,请使用 FromWavFileInput 而不是 FromDefaultMicrophoneInput

    using var audioConfig = AudioConfig.FromWavFileInput("YourAudioFile.wav");
    
  • 对于压缩的音频文件(如 MP4),请安装 GStreamer 并使用 PullAudioInputStreamPushAudioInputStream。 有关详细信息,请参阅如何使用压缩的输入音频

清理资源

可以使用 Azure 门户Azure 命令行接口 (CLI) 删除创建的语音资源。

参考文档 | 包 (NuGet) | GitHub 上的其他示例

在本快速入门中,你将创建并运行应用程序以实时识别语音并将其转录为文本。

提示

可以在 Speech Studio 中试用实时语音转文本,且无需注册或编写任何代码。

若要改为异步听录音频文件,请参阅什么是批量听录。 如果不确定哪种语音转文本解决方案适合自己,请参阅什么是语音转文本?

先决条件

设置环境

语音 SDK 以 NuGet 包的形式提供并实现了 .NET Standard 2.0。 在本指南稍后部分安装语音 SDK。 有关其他要求,请参阅安装语音 SDK

设置环境变量。

必须对应用程序进行身份验证才能访问 Azure AI 服务资源。 对于生产,请使用安全的方式存储和访问凭据。 例如,获取语音资源的密钥后,请将其写入运行应用程序的本地计算机上的新环境变量。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性

若要为语音资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  • 要设置 SPEECH_KEY 环境变量,请将“your-key”替换为你的资源的某一个密钥。
  • 要设置 SPEECH_REGION 环境变量,请将 “your-region”替换为你的资源的某一个地区。
setx SPEECH_KEY your-key
setx SPEECH_REGION your-region

注意

如果你只需要访问当前控制台中的环境变量,可使用 set(而不是 setx)来设置环境变量。

添加环境变量后,你可能需要重启任何需要读取环境变量的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

识别来自麦克风的语音

按照以下步骤创建控制台应用程序并安装语音 SDK。

  1. Visual Studio Community 中新建一个名为 SpeechRecognition 的 C++ 控制台项目。

  2. 使用 NuGet 包管理器在新项目中安装语音 SDK。

    Install-Package Microsoft.CognitiveServices.Speech
    
  3. SpeechRecognition.cpp 的内容替换为以下代码:

    #include <iostream> 
    #include <stdlib.h>
    #include <speechapi_cxx.h>
    
    using namespace Microsoft::CognitiveServices::Speech;
    using namespace Microsoft::CognitiveServices::Speech::Audio;
    
    std::string GetEnvironmentVariable(const char* name);
    
    int main()
    {
        // This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
        auto speechKey = GetEnvironmentVariable("SPEECH_KEY");
        auto speechRegion = GetEnvironmentVariable("SPEECH_REGION");
    
        if ((size(speechKey) == 0) || (size(speechRegion) == 0)) {
            std::cout << "Please set both SPEECH_KEY and SPEECH_REGION environment variables." << std::endl;
            return -1;
        }
    
        auto speechConfig = SpeechConfig::FromSubscription(speechKey, speechRegion);
    
        speechConfig->SetSpeechRecognitionLanguage("en-US");
    
        auto audioConfig = AudioConfig::FromDefaultMicrophoneInput();
        auto speechRecognizer = SpeechRecognizer::FromConfig(speechConfig, audioConfig);
    
        std::cout << "Speak into your microphone.\n";
        auto result = speechRecognizer->RecognizeOnceAsync().get();
    
        if (result->Reason == ResultReason::RecognizedSpeech)
        {
            std::cout << "RECOGNIZED: Text=" << result->Text << std::endl;
        }
        else if (result->Reason == ResultReason::NoMatch)
        {
            std::cout << "NOMATCH: Speech could not be recognized." << std::endl;
        }
        else if (result->Reason == ResultReason::Canceled)
        {
            auto cancellation = CancellationDetails::FromResult(result);
            std::cout << "CANCELED: Reason=" << (int)cancellation->Reason << std::endl;
    
            if (cancellation->Reason == CancellationReason::Error)
            {
                std::cout << "CANCELED: ErrorCode=" << (int)cancellation->ErrorCode << std::endl;
                std::cout << "CANCELED: ErrorDetails=" << cancellation->ErrorDetails << std::endl;
                std::cout << "CANCELED: Did you set the speech resource key and region values?" << std::endl;
            }
        }
    }
    
    std::string GetEnvironmentVariable(const char* name)
    {
    #if defined(_MSC_VER)
        size_t requiredSize = 0;
        (void)getenv_s(&requiredSize, nullptr, 0, name);
        if (requiredSize == 0)
        {
            return "";
        }
        auto buffer = std::make_unique<char[]>(requiredSize);
        (void)getenv_s(&requiredSize, buffer.get(), requiredSize, name);
        return buffer.get();
    #else
        auto value = getenv(name);
        return value ? value : "";
    #endif
    }
    
  4. 若要更改语音识别语言,请将 en-US 替换为其他支持的语言。 例如,使用 es-ES 表示西班牙语(西班牙)。 如果未指定语言,则默认值为 en-US。 若要详细了解如何识别可能说出的多种语言之一,请参阅语言识别

  5. 生成并运行新的控制台应用程序,从麦克风开始进行语音识别。

    重要

    确保按照设置环境变量所述设置 SPEECH_KEYSPEECH_REGION 环境变量。 如果未设置这些变量,示例会失败并显示错误消息。

  6. 当系统提示时,对着麦克风说话。 你说出的内容应该会显示为文本:

    Speak into your microphone.
    RECOGNIZED: Text=I'm excited to try speech to text.
    

备注

下面是其他一些注意事项:

  • 此示例使用 RecognizeOnceAsync 操作听录 30 秒以内的语音,或直到检测到静音。 如要详细了解长音频的持续识别(包括多语言对话),请参阅如何识别语音

  • 若要识别音频文件中的语音,请使用 FromWavFileInput 而不是 FromDefaultMicrophoneInput

    auto audioInput = AudioConfig::FromWavFileInput("YourAudioFile.wav");
    
  • 对于压缩的音频文件(如 MP4),请安装 GStreamer 并使用 PullAudioInputStreamPushAudioInputStream。 有关详细信息,请参阅如何使用压缩的输入音频

清理资源

可以使用 Azure 门户Azure 命令行接口 (CLI) 删除创建的语音资源。

参考文档 | 包 (Go) | GitHub 上的其他示例

在本快速入门中,你将创建并运行应用程序以实时识别语音并将其转录为文本。

提示

可以在 Speech Studio 中试用实时语音转文本,且无需注册或编写任何代码。

若要改为异步听录音频文件,请参阅什么是批量听录。 如果不确定哪种语音转文本解决方案适合自己,请参阅什么是语音转文本?

先决条件

设置环境

安装 Go 语音 SDK。 有关要求和说明,请参阅安装语音 SDK

设置环境变量。

必须对应用程序进行身份验证才能访问 Azure AI 服务资源。 对于生产,请使用安全的方式存储和访问凭据。 例如,获取语音资源的密钥后,请将其写入运行应用程序的本地计算机上的新环境变量。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性

若要为语音资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  • 要设置 SPEECH_KEY 环境变量,请将“your-key”替换为你的资源的某一个密钥。
  • 要设置 SPEECH_REGION 环境变量,请将 “your-region”替换为你的资源的某一个地区。
setx SPEECH_KEY your-key
setx SPEECH_REGION your-region

注意

如果你只需要访问当前控制台中的环境变量,可使用 set(而不是 setx)来设置环境变量。

添加环境变量后,你可能需要重启任何需要读取环境变量的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

识别来自麦克风的语音

按照以下步骤创建 GO 模块。

  1. 在需要新模块的位置打开命令提示符,并创建一个名为 speech-recognition.go 的新文件。

  2. 将以下代码复制到 speech-recognition.go 中:

    package main
    
    import (
        "bufio"
        "fmt"
        "os"
    
        "github.com/Microsoft/cognitive-services-speech-sdk-go/audio"
        "github.com/Microsoft/cognitive-services-speech-sdk-go/speech"
    )
    
    func sessionStartedHandler(event speech.SessionEventArgs) {
        defer event.Close()
        fmt.Println("Session Started (ID=", event.SessionID, ")")
    }
    
    func sessionStoppedHandler(event speech.SessionEventArgs) {
        defer event.Close()
        fmt.Println("Session Stopped (ID=", event.SessionID, ")")
    }
    
    func recognizingHandler(event speech.SpeechRecognitionEventArgs) {
        defer event.Close()
        fmt.Println("Recognizing:", event.Result.Text)
    }
    
    func recognizedHandler(event speech.SpeechRecognitionEventArgs) {
        defer event.Close()
        fmt.Println("Recognized:", event.Result.Text)
    }
    
    func cancelledHandler(event speech.SpeechRecognitionCanceledEventArgs) {
        defer event.Close()
        fmt.Println("Received a cancellation: ", event.ErrorDetails)
        fmt.Println("Did you set the speech resource key and region values?")
    }
    
    func main() {
        // This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
        speechKey :=  os.Getenv("SPEECH_KEY")
        speechRegion := os.Getenv("SPEECH_REGION")
    
        audioConfig, err := audio.NewAudioConfigFromDefaultMicrophoneInput()
        if err != nil {
            fmt.Println("Got an error: ", err)
            return
        }
        defer audioConfig.Close()
        speechConfig, err := speech.NewSpeechConfigFromSubscription(speechKey, speechRegion)
        if err != nil {
            fmt.Println("Got an error: ", err)
            return
        }
        defer speechConfig.Close()
        speechRecognizer, err := speech.NewSpeechRecognizerFromConfig(speechConfig, audioConfig)
        if err != nil {
            fmt.Println("Got an error: ", err)
            return
        }
        defer speechRecognizer.Close()
        speechRecognizer.SessionStarted(sessionStartedHandler)
        speechRecognizer.SessionStopped(sessionStoppedHandler)
        speechRecognizer.Recognizing(recognizingHandler)
        speechRecognizer.Recognized(recognizedHandler)
        speechRecognizer.Canceled(cancelledHandler)
        speechRecognizer.StartContinuousRecognitionAsync()
        defer speechRecognizer.StopContinuousRecognitionAsync()
        bufio.NewReader(os.Stdin).ReadBytes('\n')
    }
    
  3. 运行以下命令,创建一个 go.mod 文件并使其关联到 GitHub 上托管的组件:

    go mod init speech-recognition
    go get github.com/Microsoft/cognitive-services-speech-sdk-go
    

    重要

    确保按照设置环境变量所述设置 SPEECH_KEYSPEECH_REGION 环境变量。 如果未设置这些变量,示例会失败并显示错误消息。

  4. 生成并运行代码:

    go build
    go run speech-recognition
    

清理资源

可以使用 Azure 门户Azure 命令行接口 (CLI) 删除创建的语音资源。

参考文档 | GitHub 上的其他示例

在本快速入门中,你将创建并运行应用程序以实时识别语音并将其转录为文本。

提示

可以在 Speech Studio 中试用实时语音转文本,且无需注册或编写任何代码。

若要改为异步听录音频文件,请参阅什么是批量听录。 如果不确定哪种语音转文本解决方案适合自己,请参阅什么是语音转文本?

先决条件

设置环境

需要先安装语音 SDK,然后才能执行其他操作。 本快速入门中的示例适用于 Java 运行时

  1. 安装 Apache Maven。 然后运行 mvn -v 以确认安装成功。

  2. 在项目的根目录中创建一个新的 pom.xml 文件,并将以下代码复制到该文件中:

    <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.microsoft.cognitiveservices.speech.samples</groupId>
        <artifactId>quickstart-eclipse</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <build>
            <sourceDirectory>src</sourceDirectory>
            <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                <source>1.8</source>
                <target>1.8</target>
                </configuration>
            </plugin>
            </plugins>
        </build>
        <dependencies>
            <dependency>
            <groupId>com.microsoft.cognitiveservices.speech</groupId>
            <artifactId>client-sdk</artifactId>
            <version>1.34.1</version>
            </dependency>
        </dependencies>
    </project>
    
  3. 安装语音 SDK 和依赖项。

    mvn clean dependency:copy-dependencies
    

设置环境变量。

必须对应用程序进行身份验证才能访问 Azure AI 服务资源。 对于生产,请使用安全的方式存储和访问凭据。 例如,获取语音资源的密钥后,请将其写入运行应用程序的本地计算机上的新环境变量。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性

若要为语音资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  • 要设置 SPEECH_KEY 环境变量,请将“your-key”替换为你的资源的某一个密钥。
  • 要设置 SPEECH_REGION 环境变量,请将 “your-region”替换为你的资源的某一个地区。
setx SPEECH_KEY your-key
setx SPEECH_REGION your-region

注意

如果你只需要访问当前控制台中的环境变量,可使用 set(而不是 setx)来设置环境变量。

添加环境变量后,你可能需要重启任何需要读取环境变量的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

识别来自麦克风的语音

按照以下步骤创建用于语音识别的控制台应用程序。

  1. 在同一项目根目录中创建名为 SpeechRecognition.java 的新文件。

  2. 将以下代码复制到 SpeechRecognition.java 中:

    import com.microsoft.cognitiveservices.speech.*;
    import com.microsoft.cognitiveservices.speech.audio.AudioConfig;
    
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.Future;
    
    public class SpeechRecognition {
        // This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
        private static String speechKey = System.getenv("SPEECH_KEY");
        private static String speechRegion = System.getenv("SPEECH_REGION");
    
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            SpeechConfig speechConfig = SpeechConfig.fromSubscription(speechKey, speechRegion);
            speechConfig.setSpeechRecognitionLanguage("en-US");
            recognizeFromMicrophone(speechConfig);
        }
    
        public static void recognizeFromMicrophone(SpeechConfig speechConfig) throws InterruptedException, ExecutionException {
            AudioConfig audioConfig = AudioConfig.fromDefaultMicrophoneInput();
            SpeechRecognizer speechRecognizer = new SpeechRecognizer(speechConfig, audioConfig);
    
            System.out.println("Speak into your microphone.");
            Future<SpeechRecognitionResult> task = speechRecognizer.recognizeOnceAsync();
            SpeechRecognitionResult speechRecognitionResult = task.get();
    
            if (speechRecognitionResult.getReason() == ResultReason.RecognizedSpeech) {
                System.out.println("RECOGNIZED: Text=" + speechRecognitionResult.getText());
            }
            else if (speechRecognitionResult.getReason() == ResultReason.NoMatch) {
                System.out.println("NOMATCH: Speech could not be recognized.");
            }
            else if (speechRecognitionResult.getReason() == ResultReason.Canceled) {
                CancellationDetails cancellation = CancellationDetails.fromResult(speechRecognitionResult);
                System.out.println("CANCELED: Reason=" + cancellation.getReason());
    
                if (cancellation.getReason() == CancellationReason.Error) {
                    System.out.println("CANCELED: ErrorCode=" + cancellation.getErrorCode());
                    System.out.println("CANCELED: ErrorDetails=" + cancellation.getErrorDetails());
                    System.out.println("CANCELED: Did you set the speech resource key and region values?");
                }
            }
    
            System.exit(0);
        }
    }
    
  3. 若要更改语音识别语言,请将 en-US 替换为其他支持的语言。 例如,使用 es-ES 表示西班牙语(西班牙)。 如果未指定语言,则默认值为 en-US。 若要详细了解如何识别可能说出的多种语言之一,请参阅语言识别

  4. 运行新的控制台应用程序,从麦克风开始进行语音识别:

    javac SpeechRecognition.java -cp ".;target\dependency\*"
    java -cp ".;target\dependency\*" SpeechRecognition
    

    重要

    确保按照设置环境变量所述设置 SPEECH_KEYSPEECH_REGION 环境变量。 如果未设置这些变量,示例会失败并显示错误消息。

  5. 当系统提示时,对着麦克风说话。 你说出的内容应该会显示为文本:

    Speak into your microphone.
    RECOGNIZED: Text=I'm excited to try speech to text.
    

备注

下面是其他一些注意事项:

  • 此示例使用 RecognizeOnceAsync 操作听录 30 秒以内的语音,或直到检测到静音。 如要详细了解长音频的持续识别(包括多语言对话),请参阅如何识别语音

  • 若要识别音频文件中的语音,请使用 fromWavFileInput 而不是 fromDefaultMicrophoneInput

    AudioConfig audioConfig = AudioConfig.fromWavFileInput("YourAudioFile.wav");
    
  • 对于压缩的音频文件(如 MP4),请安装 GStreamer 并使用 PullAudioInputStreamPushAudioInputStream。 有关详细信息,请参阅如何使用压缩的输入音频

清理资源

可以使用 Azure 门户Azure 命令行接口 (CLI) 删除创建的语音资源。

参考文档 | 包 (npm) | GitHub 上的其他示例 | 库源代码

在本快速入门中,你将创建并运行应用程序以实时识别语音并将其转录为文本。

提示

可以在 Speech Studio 中试用实时语音转文本,且无需注册或编写任何代码。

若要改为异步听录音频文件,请参阅什么是批量听录。 如果不确定哪种语音转文本解决方案适合自己,请参阅什么是语音转文本?

先决条件

还需要本地计算机上的 .wav 音频文件。 可使用自己的 .wav 文件(最长 30 秒),或者下载 https://crbn.us/whatstheweatherlike.wav 示例文件。

设置环境

需要先安装适用于 JavaScript 的语音 SDK,然后才能执行其他操作。 运行以下命令:npm install microsoft-cognitiveservices-speech-sdk。 有关安装说明指南,请参阅安装语音 SDK

设置环境变量。

必须对应用程序进行身份验证才能访问 Azure AI 服务资源。 对于生产,请使用安全的方式存储和访问凭据。 例如,获取语音资源的密钥后,请将其写入运行应用程序的本地计算机上的新环境变量。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性

若要为语音资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  • 要设置 SPEECH_KEY 环境变量,请将“your-key”替换为你的资源的某一个密钥。
  • 要设置 SPEECH_REGION 环境变量,请将 “your-region”替换为你的资源的某一个地区。
setx SPEECH_KEY your-key
setx SPEECH_REGION your-region

注意

如果你只需要访问当前控制台中的环境变量,可使用 set(而不是 setx)来设置环境变量。

添加环境变量后,你可能需要重启任何需要读取环境变量的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

从文件中识别语音

按照以下步骤创建用于语音识别的 Node.js 控制台应用程序。

  1. 在需要新项目的位置打开命令提示符,并创建一个名为 SpeechRecognition.js 的文件。

  2. 安装适用于 JavaScript 的语音 SDK:

    npm install microsoft-cognitiveservices-speech-sdk
    
  3. 将以下代码复制到 SpeechRecognition.js 中:

    const fs = require("fs");
    const sdk = require("microsoft-cognitiveservices-speech-sdk");
    
    // This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
    const speechConfig = sdk.SpeechConfig.fromSubscription(process.env.SPEECH_KEY, process.env.SPEECH_REGION);
    speechConfig.speechRecognitionLanguage = "en-US";
    
    function fromFile() {
        let audioConfig = sdk.AudioConfig.fromWavFileInput(fs.readFileSync("YourAudioFile.wav"));
        let speechRecognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig);
    
        speechRecognizer.recognizeOnceAsync(result => {
            switch (result.reason) {
                case sdk.ResultReason.RecognizedSpeech:
                    console.log(`RECOGNIZED: Text=${result.text}`);
                    break;
                case sdk.ResultReason.NoMatch:
                    console.log("NOMATCH: Speech could not be recognized.");
                    break;
                case sdk.ResultReason.Canceled:
                    const cancellation = sdk.CancellationDetails.fromResult(result);
                    console.log(`CANCELED: Reason=${cancellation.reason}`);
    
                    if (cancellation.reason == sdk.CancellationReason.Error) {
                        console.log(`CANCELED: ErrorCode=${cancellation.ErrorCode}`);
                        console.log(`CANCELED: ErrorDetails=${cancellation.errorDetails}`);
                        console.log("CANCELED: Did you set the speech resource key and region values?");
                    }
                    break;
            }
            speechRecognizer.close();
        });
    }
    fromFile();
    
  4. 在 SpeechRecognition.js 中,将 YourAudioFile.wav 替换为你自己的 .wav 文件。 此示例仅识别 .wav 文件中的语音。 有关其他音频格式的信息,请参阅如何使用压缩的输入音频。 此示例支持最长 30 秒的音频。

  5. 若要更改语音识别语言,请将 en-US 替换为其他支持的语言。 例如,使用 es-ES 表示西班牙语(西班牙)。 如果未指定语言,则默认值为 en-US。 若要详细了解如何识别可能说出的多种语言之一,请参阅语言识别

  6. 运行新的控制台应用程序,从文件开始进行语音识别:

    node.exe SpeechRecognition.js
    

    重要

    确保按照设置环境变量所述设置 SPEECH_KEYSPEECH_REGION 环境变量。 如果未设置这些变量,示例会失败并显示错误消息。

    音频文件中的语音应以文本的形式输出:

    RECOGNIZED: Text=I'm excited to try speech to text.
    

备注

此示例使用 recognizeOnceAsync 操作听录 30 秒以内的语音,或直到检测到静音。 如要详细了解长音频的持续识别(包括多语言对话),请参阅如何识别语音

备注

Node.js 中不支持识别来自麦克风的语音。 仅在基于浏览器的 JavaScript 环境中支持该功能。 有关详细信息,请参阅 GitHub 上的 React 示例从麦克风实现语音转文本

React 示例演示身份验证令牌交换和管理的设计模式。 该示例还演示如何从麦克风或文件捕获音频以进行语音转文本转换。

清理资源

可以使用 Azure 门户Azure 命令行接口 (CLI) 删除创建的语音资源。

参考文档 | 包(下载) | GitHub 上的其他示例

在本快速入门中,你将创建并运行应用程序以实时识别语音并将其转录为文本。

提示

可以在 Speech Studio 中试用实时语音转文本,且无需注册或编写任何代码。

若要改为异步听录音频文件,请参阅什么是批量听录。 如果不确定哪种语音转文本解决方案适合自己,请参阅什么是语音转文本?

先决条件

设置环境

适用于 Objective-C 的语音 SDK 目前以框架捆绑包的形式分发。 框架同时在 iOS 和 macOS 上支持 Objective-C 和 Swift。

可在 Xcode 项目中将语音 SDK 用作 CocoaPod,也可以直接下载并手动与其建立链接。 本指南使用 CocoaPod。 根据安装说明中所述,安装 CocoaPod 依赖项管理器。

设置环境变量。

必须对应用程序进行身份验证才能访问 Azure AI 服务资源。 对于生产,请使用安全的方式存储和访问凭据。 例如,获取语音资源的密钥后,请将其写入运行应用程序的本地计算机上的新环境变量。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性

若要为语音资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  • 要设置 SPEECH_KEY 环境变量,请将“your-key”替换为你的资源的某一个密钥。
  • 要设置 SPEECH_REGION 环境变量,请将 “your-region”替换为你的资源的某一个地区。
setx SPEECH_KEY your-key
setx SPEECH_REGION your-region

注意

如果你只需要访问当前控制台中的环境变量,可使用 set(而不是 setx)来设置环境变量。

添加环境变量后,你可能需要重启任何需要读取环境变量的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

识别来自麦克风的语音

按照以下步骤识别 macOS 应用程序中的语音。

  1. 克隆 Azure-Samples/cognitive-services-speech-sdk 存储库,以在 macOS 上获取来自麦克风且以 Objective-C 编写的识别语音示例项目。 此存储库还包含 iOS 示例。

  2. 在控制台窗口中,导航到下载的示例应用 helloworld 的目录。

  3. 运行 pod install 命令。 此命令生成一个 helloworld.xcworkspace Xcode 工作区,其中包含示例应用以及用作依赖项的语音 SDK。

  4. 在 Xcode 中打开 helloworld.xcworkspace 工作区。

  5. 打开名为 AppDelegate.m 的文件,并找到 buttonPressed 方法,如下所示。

    - (void)buttonPressed:(NSButton *)button {
        // Creates an instance of a speech config with specified subscription key and service region.
        NSString *speechKey = [[[NSProcessInfo processInfo] environment] objectForKey:@"SPEECH_KEY"];
        NSString *serviceRegion = [[[NSProcessInfo processInfo] environment] objectForKey:@"SPEECH_REGION"];
    
        SPXAudioConfiguration *audioConfig = [[SPXAudioConfiguration alloc] initWithMicrophone:nil];
        SPXSpeechConfiguration *speechConfig = [[SPXSpeechConfiguration alloc] initWithSubscription:speechKey region:serviceRegion];
        SPXSpeechRecognizer *speechRecognizer = [[SPXSpeechRecognizer alloc] initWithSpeechConfiguration:speechConfig language:@"en-US" audioConfiguration:audioConfig];
    
        NSLog(@"Speak into your microphone.");
    
        SPXSpeechRecognitionResult *speechResult = [speechRecognizer recognizeOnce];
    
        // Checks result.
        if (SPXResultReason_Canceled == speechResult.reason) {
            SPXCancellationDetails *details = [[SPXCancellationDetails alloc] initFromCanceledRecognitionResult:speechResult];
            NSLog(@"Speech recognition was canceled: %@. Did you set the speech resource key and region values?", details.errorDetails);
            [self.label setStringValue:([NSString stringWithFormat:@"Canceled: %@", details.errorDetails])];
        } else if (SPXResultReason_RecognizedSpeech == speechResult.reason) {
            NSLog(@"Speech recognition result received: %@", speechResult.text);
            [self.label setStringValue:(speechResult.text)];
        } else {
            NSLog(@"There was an error.");
            [self.label setStringValue:(@"Speech Recognition Error")];
        }
    }
    
  6. 在 AppDelegate.m 中,使用先前为语音资源密钥和区域设置的环境变量

    NSString *speechKey = [[[NSProcessInfo processInfo] environment] objectForKey:@"SPEECH_KEY"];
    NSString *serviceRegion = [[[NSProcessInfo processInfo] environment] objectForKey:@"SPEECH_REGION"];
    
  7. 若要更改语音识别语言,请将 en-US 替换为其他支持的语言。 例如,使用 es-ES 表示西班牙语(西班牙)。 如果未指定语言,则默认值为 en-US。 若要详细了解如何识别可能说出的多种语言之一,请参阅语言识别

  8. 要使调试输出可见,请选择“视图”>“调试区域”>“激活控制台”。

  9. 在菜单中选择“产品”>“运行”,或者选择“播放”按钮,以生成并运行示例代码。

重要

确保按照设置环境变量所述设置 SPEECH_KEYSPEECH_REGION 环境变量。 如果未设置这些变量,示例会失败并显示错误消息。

选择应用中按钮并讲几句话后,应会在屏幕下方看到讲出的文本。 首次运行该应用时,系统应会提示你授予应用访问计算机麦克风的权限。

备注

下面是其他一些注意事项:

  • 此示例使用 recognizeOnce 操作听录 30 秒以内的语音,或直到检测到静音。 如要详细了解长音频的持续识别(包括多语言对话),请参阅如何识别语音

  • 若要识别音频文件中的语音,请使用 initWithWavFileInput 而不是 initWithMicrophone

    SPXAudioConfiguration *audioConfig = [[SPXAudioConfiguration alloc] initWithWavFileInput:YourAudioFile];
    

清理资源

可以使用 Azure 门户Azure 命令行接口 (CLI) 删除创建的语音资源。

参考文档 | 包(下载) | GitHub 上的其他示例

在本快速入门中,你将创建并运行应用程序以实时识别语音并将其转录为文本。

提示

可以在 Speech Studio 中试用实时语音转文本,且无需注册或编写任何代码。

若要改为异步听录音频文件,请参阅什么是批量听录。 如果不确定哪种语音转文本解决方案适合自己,请参阅什么是语音转文本?

先决条件

设置环境

适用于 Swift 的语音 SDK 目前以框架捆绑包的形式分发。 框架同时在 iOS 和 macOS 上支持 Objective-C 和 Swift。

可在 Xcode 项目中将语音 SDK 用作 CocoaPod,也可以直接下载并手动与其建立链接。 本指南使用 CocoaPod。 根据安装说明中所述,安装 CocoaPod 依赖项管理器。

设置环境变量。

必须对应用程序进行身份验证才能访问 Azure AI 服务资源。 对于生产,请使用安全的方式存储和访问凭据。 例如,获取语音资源的密钥后,请将其写入运行应用程序的本地计算机上的新环境变量。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性

若要为语音资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  • 要设置 SPEECH_KEY 环境变量,请将“your-key”替换为你的资源的某一个密钥。
  • 要设置 SPEECH_REGION 环境变量,请将 “your-region”替换为你的资源的某一个地区。
setx SPEECH_KEY your-key
setx SPEECH_REGION your-region

注意

如果你只需要访问当前控制台中的环境变量,可使用 set(而不是 setx)来设置环境变量。

添加环境变量后,你可能需要重启任何需要读取环境变量的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

识别来自麦克风的语音

按照以下步骤识别 macOS 应用程序中的语音。

  1. 克隆 Azure-Samples/cognitive-services-speech-sdk 存储库,以在 macOS 上获取来自麦克风且以 Swift 编写的识别语音示例项目。 此存储库还包含 iOS 示例。

  2. 在终端中导航到已下载的示例应用 (helloworld) 的目录。

  3. 运行 pod install 命令。 此命令生成一个 helloworld.xcworkspace Xcode 工作区,其中包含示例应用以及用作依赖项的语音 SDK。

  4. 在 Xcode 中打开 helloworld.xcworkspace 工作区。

  5. 打开名为 AppDelegate.swift 的文件,并找到 applicationDidFinishLaunchingrecognizeFromMic 方法,如下所示。

    import Cocoa
    
    @NSApplicationMain
    class AppDelegate: NSObject, NSApplicationDelegate {
        var label: NSTextField!
        var fromMicButton: NSButton!
    
        var sub: String!
        var region: String!
    
        @IBOutlet weak var window: NSWindow!
    
        func applicationDidFinishLaunching(_ aNotification: Notification) {
            print("loading")
            // load subscription information
            sub = ProcessInfo.processInfo.environment["SPEECH_KEY"]
            region = ProcessInfo.processInfo.environment["SPEECH_REGION"]
    
            label = NSTextField(frame: NSRect(x: 100, y: 50, width: 200, height: 200))
            label.textColor = NSColor.black
            label.lineBreakMode = .byWordWrapping
    
            label.stringValue = "Recognition Result"
            label.isEditable = false
    
            self.window.contentView?.addSubview(label)
    
            fromMicButton = NSButton(frame: NSRect(x: 100, y: 300, width: 200, height: 30))
            fromMicButton.title = "Recognize"
            fromMicButton.target = self
            fromMicButton.action = #selector(fromMicButtonClicked)
            self.window.contentView?.addSubview(fromMicButton)
        }
    
        @objc func fromMicButtonClicked() {
            DispatchQueue.global(qos: .userInitiated).async {
                self.recognizeFromMic()
            }
        }
    
        func recognizeFromMic() {
            var speechConfig: SPXSpeechConfiguration?
            do {
                try speechConfig = SPXSpeechConfiguration(subscription: sub, region: region)
            } catch {
                print("error \(error) happened")
                speechConfig = nil
            }
            speechConfig?.speechRecognitionLanguage = "en-US"
    
            let audioConfig = SPXAudioConfiguration()
    
            let reco = try! SPXSpeechRecognizer(speechConfiguration: speechConfig!, audioConfiguration: audioConfig)
    
            reco.addRecognizingEventHandler() {reco, evt in
                print("intermediate recognition result: \(evt.result.text ?? "(no result)")")
                self.updateLabel(text: evt.result.text, color: .gray)
            }
    
            updateLabel(text: "Listening ...", color: .gray)
            print("Listening...")
    
            let result = try! reco.recognizeOnce()
            print("recognition result: \(result.text ?? "(no result)"), reason: \(result.reason.rawValue)")
            updateLabel(text: result.text, color: .black)
    
            if result.reason != SPXResultReason.recognizedSpeech {
                let cancellationDetails = try! SPXCancellationDetails(fromCanceledRecognitionResult: result)
                print("cancelled: \(result.reason), \(cancellationDetails.errorDetails)")
                print("Did you set the speech resource key and region values?")
                updateLabel(text: "Error: \(cancellationDetails.errorDetails)", color: .red)
            }
        }
    
        func updateLabel(text: String?, color: NSColor) {
            DispatchQueue.main.async {
                self.label.stringValue = text!
                self.label.textColor = color
            }
        }
    }
    
  6. 在 AppDelegate.m 中,使用先前为语音资源密钥和区域设置的环境变量

    sub = ProcessInfo.processInfo.environment["SPEECH_KEY"]
    region = ProcessInfo.processInfo.environment["SPEECH_REGION"]
    
  7. 若要更改语音识别语言,请将 en-US 替换为其他支持的语言。 例如,使用 es-ES 表示西班牙语(西班牙)。 如果未指定语言,则默认值为 en-US。 若要详细了解如何识别可能说出的多种语言之一,请参阅语言识别

  8. 要使调试输出可见,请选择“视图”>“调试区域”>“激活控制台”。

  9. 在菜单中选择“产品”>“运行”,或者选择“播放”按钮,以生成并运行示例代码。

    重要

    确保按照设置环境变量所述设置 SPEECH_KEYSPEECH_REGION 环境变量。 如果未设置这些变量,示例会失败并显示错误消息。

选择应用中按钮并讲几句话后,应会在屏幕下方看到讲出的文本。 首次运行该应用时,系统应会提示你授予应用访问计算机麦克风的权限。

备注

此示例使用 recognizeOnce 操作听录 30 秒以内的语音,或直到检测到静音。 如要详细了解长音频的持续识别(包括多语言对话),请参阅如何识别语音

清理资源

可以使用 Azure 门户Azure 命令行接口 (CLI) 删除创建的语音资源。

参考文档 | 包 (PyPi) | GitHub 上的其他示例

在本快速入门中,你将创建并运行应用程序以实时识别语音并将其转录为文本。

提示

可以在 Speech Studio 中试用实时语音转文本,且无需注册或编写任何代码。

若要改为异步听录音频文件,请参阅什么是批量听录。 如果不确定哪种语音转文本解决方案适合自己,请参阅什么是语音转文本?

先决条件

设置环境

适用于 Python 的语音 SDK 可用作 Python 包索引 (PyPI) 模块。 适用于 Python 的语音 SDK 与 Windows、Linux 和 macOS 兼容。

安装从 3.7 开始或更高版本的 Python。 有关其他要求,请参阅安装语音 SDK

设置环境变量。

必须对应用程序进行身份验证才能访问 Azure AI 服务资源。 对于生产,请使用安全的方式存储和访问凭据。 例如,获取语音资源的密钥后,请将其写入运行应用程序的本地计算机上的新环境变量。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性

若要为语音资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  • 要设置 SPEECH_KEY 环境变量,请将“your-key”替换为你的资源的某一个密钥。
  • 要设置 SPEECH_REGION 环境变量,请将 “your-region”替换为你的资源的某一个地区。
setx SPEECH_KEY your-key
setx SPEECH_REGION your-region

注意

如果你只需要访问当前控制台中的环境变量,可使用 set(而不是 setx)来设置环境变量。

添加环境变量后,你可能需要重启任何需要读取环境变量的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

识别来自麦克风的语音

按照以下步骤创建控制台应用程序。

  1. 在需要新项目的位置打开命令提示符,并创建一个名为 speech_recognition.py 的文件。

  2. 运行此命令以安装语音 SDK:

    pip install azure-cognitiveservices-speech
    
  3. 将以下代码复制到 speech_recognition.py 中:

    import os
    import azure.cognitiveservices.speech as speechsdk
    
    def recognize_from_microphone():
        # This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
        speech_config = speechsdk.SpeechConfig(subscription=os.environ.get('SPEECH_KEY'), region=os.environ.get('SPEECH_REGION'))
        speech_config.speech_recognition_language="en-US"
    
        audio_config = speechsdk.audio.AudioConfig(use_default_microphone=True)
        speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)
    
        print("Speak into your microphone.")
        speech_recognition_result = speech_recognizer.recognize_once_async().get()
    
        if speech_recognition_result.reason == speechsdk.ResultReason.RecognizedSpeech:
            print("Recognized: {}".format(speech_recognition_result.text))
        elif speech_recognition_result.reason == speechsdk.ResultReason.NoMatch:
            print("No speech could be recognized: {}".format(speech_recognition_result.no_match_details))
        elif speech_recognition_result.reason == speechsdk.ResultReason.Canceled:
            cancellation_details = speech_recognition_result.cancellation_details
            print("Speech Recognition canceled: {}".format(cancellation_details.reason))
            if cancellation_details.reason == speechsdk.CancellationReason.Error:
                print("Error details: {}".format(cancellation_details.error_details))
                print("Did you set the speech resource key and region values?")
    
    recognize_from_microphone()
    
  4. 若要更改语音识别语言,请将 en-US 替换为其他支持的语言。 例如,使用 es-ES 表示西班牙语(西班牙)。 如果未指定语言,则默认值为 en-US。 若要详细了解如何从多种使用的语言中进行识别,请参阅语言识别

  5. 运行新的控制台应用程序,从麦克风开始进行语音识别:

    python speech_recognition.py
    

    重要

    确保按照设置环境变量所述设置 SPEECH_KEYSPEECH_REGION 环境变量。 如果未设置这些变量,示例会失败并显示错误消息。

  6. 当系统提示时,对着麦克风说话。 你说出的内容应该会显示为文本:

    Speak into your microphone.
    RECOGNIZED: Text=I'm excited to try speech to text.
    

备注

下面是其他一些注意事项:

  • 此示例使用 recognize_once_async 操作听录 30 秒以内的语音,或直到检测到静音。 如要详细了解长音频的持续识别(包括多语言对话),请参阅如何识别语音

  • 若要识别音频文件中的语音,请使用 filename 而不是 use_default_microphone

    audio_config = speechsdk.audio.AudioConfig(filename="YourAudioFile.wav")
    
  • 对于压缩的音频文件(如 MP4),请安装 GStreamer 并使用 PullAudioInputStreamPushAudioInputStream。 有关详细信息,请参阅如何使用压缩的输入音频

清理资源

可以使用 Azure 门户Azure 命令行接口 (CLI) 删除创建的语音资源。

语音转文本 REST API 参考 | 适用于短音频的语音转文本 REST API 参考 | 有关 GitHub 的其他示例

在本快速入门中,你将创建并运行应用程序以实时识别语音并将其转录为文本。

提示

可以在 Speech Studio 中试用实时语音转文本,且无需注册或编写任何代码。

若要改为异步听录音频文件,请参阅什么是批量听录。 如果不确定哪种语音转文本解决方案适合自己,请参阅什么是语音转文本?

先决条件

还需要本地计算机上的 .wav 音频文件。 可使用自己的 .wav 文件(最长 60 秒),或者下载 https://crbn.us/whatstheweatherlike.wav 示例文件。

设置环境变量。

必须对应用程序进行身份验证才能访问 Azure AI 服务资源。 对于生产,请使用安全的方式存储和访问凭据。 例如,获取语音资源的密钥后,请将其写入运行应用程序的本地计算机上的新环境变量。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性

若要为语音资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  • 要设置 SPEECH_KEY 环境变量,请将“your-key”替换为你的资源的某一个密钥。
  • 要设置 SPEECH_REGION 环境变量,请将 “your-region”替换为你的资源的某一个地区。
setx SPEECH_KEY your-key
setx SPEECH_REGION your-region

注意

如果你只需要访问当前控制台中的环境变量,可使用 set(而不是 setx)来设置环境变量。

添加环境变量后,你可能需要重启任何需要读取环境变量的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

从文件中识别语音

打开控制台窗口并运行以下 cURL 命令。 将 YourAudioFile.wav 替换为你的音频文件的路径和名称。

curl --location --request POST "https://%SPEECH_REGION%.stt.speech.azure.cn/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=detailed" ^
--header "Ocp-Apim-Subscription-Key: %SPEECH_KEY%" ^
--header "Content-Type: audio/wav" ^
--data-binary "@YourAudioFile.wav"

重要

确保按照设置环境变量所述设置 SPEECH_KEYSPEECH_REGION 环境变量。 如果未设置这些变量,示例会失败并显示错误消息。

应会收到类似于此处所示的响应。 DisplayText 应为从音频文件中识别的文本。 该命令可识别长达 60 秒的音频,并将其转换为文本。

{
    "RecognitionStatus": "Success",
    "DisplayText": "My voice is my passport, verify me.",
    "Offset": 6600000,
    "Duration": 32100000
}

有关详细信息,请参阅适用于短音频的语音转文本 REST API

清理资源

可以使用 Azure 门户Azure 命令行接口 (CLI) 删除创建的语音资源。

在本快速入门中,你将创建并运行应用程序以实时识别语音并将其转录为文本。

提示

可以在 Speech Studio 中试用实时语音转文本,且无需注册或编写任何代码。

若要改为异步听录音频文件,请参阅什么是批量听录。 如果不确定哪种语音转文本解决方案适合自己,请参阅什么是语音转文本?

先决条件

设置环境

请按照以下步骤操作,并参阅语音 CLI 快速入门,了解适用于你的平台的其他要求。

  1. 运行以下 .NET CLI 命令以安装语音 CLI:

    dotnet tool install --global Microsoft.CognitiveServices.Speech.CLI
    
  2. 运行以下命令以配置你的语音资源密钥和区域。 将 SUBSCRIPTION-KEY 替换为语音资源密钥,将 REGION 替换为语音资源区域。

    spx config @key --set SUBSCRIPTION-KEY
    spx config @region --set REGION
    

识别来自麦克风的语音

  1. 运行以下命令,从麦克风开始进行语音识别:

    spx recognize --microphone --source en-US
    
  2. 对麦克风说话,随后可以看到字词会实时转录为文本。 如果停止说话一段时间(30 秒),或者选择 Ctrl+C,语音 CLI 将停止。

    Connection CONNECTED...
    RECOGNIZED: I'm excited to try speech to text.
    

备注

下面是其他一些注意事项:

  • 若要识别音频文件中的语音,请使用 --file 而不是 --microphone。 对于压缩的音频文件(如 MP4),请安装 GStreamer 并使用 --format。 有关详细信息,请参阅如何使用压缩的输入音频

    spx recognize --file YourAudioFile.wav
    spx recognize --file YourAudioFile.mp4 --format any
    
  • 若要提高特定字词或语句的识别准确性,请使用短语列表。 你可以在行中包含短语列表,也可以使用文本文件以及识别命令:

    spx recognize --microphone --phrases "Contoso;Jessie;Rehaan;"
    spx recognize --microphone --phrases @phrases.txt
    
  • 若要更改语音识别语言,请将 en-US 替换为其他支持的语言。 例如,使用 es-ES 表示西班牙语(西班牙)。 如果未指定语言,则默认值为 en-US

    spx recognize --microphone --source es-ES
    
  • 若要连续识别超过 30 秒的音频,请追加 --continuous

    spx recognize --microphone --source es-ES --continuous
    
  • 运行以下命令,了解更多语音识别选项,例如文件输入和输出:

    spx help recognize
    

清理资源

可以使用 Azure 门户Azure 命令行接口 (CLI) 删除创建的语音资源。

后续步骤