快速入门:识别语音并将其翻译为文本

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

在本快速入门中,你将运行一个应用程序将一种语言的语音翻译成另一种语言的文本。

先决条件

设置环境

语音 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;
    using Microsoft.CognitiveServices.Speech.Translation;
    
    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(TranslationRecognitionResult translationRecognitionResult)
        {
            switch (translationRecognitionResult.Reason)
            {
                case ResultReason.TranslatedSpeech:
                    Console.WriteLine($"RECOGNIZED: Text={translationRecognitionResult.Text}");
                    foreach (var element in translationRecognitionResult.Translations)
                    {
                        Console.WriteLine($"TRANSLATED into '{element.Key}': {element.Value}");
                    }
                    break;
                case ResultReason.NoMatch:
                    Console.WriteLine($"NOMATCH: Speech could not be recognized.");
                    break;
                case ResultReason.Canceled:
                    var cancellation = CancellationDetails.FromResult(translationRecognitionResult);
                    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 speechTranslationConfig = SpeechTranslationConfig.FromSubscription(speechKey, speechRegion);        
            speechTranslationConfig.SpeechRecognitionLanguage = "en-US";
            speechTranslationConfig.AddTargetLanguage("it");
    
            using var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
            using var translationRecognizer = new TranslationRecognizer(speechTranslationConfig, audioConfig);
    
            Console.WriteLine("Speak into your microphone.");
            var translationRecognitionResult = await translationRecognizer.RecognizeOnceAsync();
            OutputSpeechRecognitionResult(translationRecognitionResult);
        }
    }
    
  4. 若要更改语音识别语言,请将 en-US 替换为其他支持的语言。 使用短划线 (-) 分隔符指定完整的区域设置。 例如,es-ES 代表西班牙语(西班牙)。 如果未指定语言,则默认语言为 en-US。 若要详细了解如何从多种使用的语言中进行识别,请参阅语言识别

  5. 若要更改翻译目标语言,请将 it 替换为其他支持的语言。 除了少数例外,只需指定区域设置短划线 (-) 分隔符之前的语言代码。 例如,对于西班牙语(西班牙)使用 es(而不是 es-ES)。 如果未指定语言,则默认语言为 en

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

dotnet run

当系统提示时,对着麦克风说话。 你所说的内容应以目标语言的翻译文本形式输出:

Speak into your microphone.
RECOGNIZED: Text=I'm excited to try speech translation.
TRANSLATED into 'it': Sono entusiasta di provare la traduzione vocale.

注解

你现已完成快速入门,下面是一些其他注意事项:

  • 此示例使用 RecognizeOnceAsync 操作听录 30 秒以内的语音,或直到检测到静音。
  • 若要从音频文件中识别语音,请使用 FromWavFileInput,不要使用 FromDefaultMicrophoneInput
    using var audioConfig = AudioConfig.FromWavFileInput("YourAudioFile.wav");
    
  • 对于压缩的音频文件(如 MP4),请安装 GStreamer 并使用 PullAudioInputStreamPushAudioInputStream。 有关详细信息,请参阅如何使用压缩的输入音频

清理资源

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

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

在本快速入门中,你将运行一个应用程序将一种语言的语音翻译成另一种语言的文本。

先决条件

设置环境

语音 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 2022 中创建一个名为 SpeechTranslation 的新 C++ 控制台项目。

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

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

    #include <iostream> 
    #include <stdlib.h>
    #include <speechapi_cxx.h>
    
    using namespace Microsoft::CognitiveServices::Speech;
    using namespace Microsoft::CognitiveServices::Speech::Audio;
    using namespace Microsoft::CognitiveServices::Speech::Translation;
    
    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");
    
        auto speechTranslationConfig = SpeechTranslationConfig::FromSubscription(speechKey, speechRegion);
        speechTranslationConfig->SetSpeechRecognitionLanguage("en-US");
        speechTranslationConfig->AddTargetLanguage("it");
    
        auto audioConfig = AudioConfig::FromDefaultMicrophoneInput();
        auto translationRecognizer = TranslationRecognizer::FromConfig(speechTranslationConfig, audioConfig);
    
        std::cout << "Speak into your microphone.\n";
        auto result = translationRecognizer->RecognizeOnceAsync().get();
    
        if (result->Reason == ResultReason::TranslatedSpeech)
        {
            std::cout << "RECOGNIZED: Text=" << result->Text << std::endl;
            for (auto pair : result->Translations)
            {
                auto language = pair.first;
                auto translation = pair.second;
                std::cout << "Translated into '" << language << "': " << translation << 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. 若要更改翻译目标语言,请将 it 替换为其他支持的语言。 除了少数例外,只需指定区域设置短划线 (-) 分隔符之前的语言代码。 例如,对于西班牙语(西班牙)使用 es(而不是 es-ES)。 如果未指定语言,则默认语言为 en

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

当系统提示时,对着麦克风说话。 你所说的内容应以目标语言的翻译文本形式输出:

Speak into your microphone.
RECOGNIZED: Text=I'm excited to try speech translation.
Translated into 'it': Sono entusiasta di provare la traduzione vocale.

注解

你现已完成快速入门,下面是一些其他注意事项:

  • 此示例使用 RecognizeOnceAsync 操作听录 30 秒以内的语音,或直到检测到静音。
  • 若要从音频文件中识别语音,请使用 FromWavFileInput,不要使用 FromDefaultMicrophoneInput
    auto audioInput = AudioConfig::FromWavFileInput("YourAudioFile.wav");
    
  • 对于压缩的音频文件(如 MP4),请安装 GStreamer 并使用 PullAudioInputStreamPushAudioInputStream。 有关详细信息,请参阅如何使用压缩的输入音频

清理资源

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

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

适用于 Go 的语音 SDK 不支持语音翻译。 请选择其他编程语言,或从本文开头链接的 Go 引用和示例。

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

在本快速入门中,你将运行一个应用程序将一种语言的语音翻译成另一种语言的文本。

先决条件

设置环境

需要先安装语音 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.35.0</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. 在同一项目根目录中创建一个名为 SpeechTranslation.java 的新文件。

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

    import com.microsoft.cognitiveservices.speech.*;
    import com.microsoft.cognitiveservices.speech.audio.AudioConfig;
    import com.microsoft.cognitiveservices.speech.translation.*;
    
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.Future;
    import java.util.Map;
    
    public class SpeechTranslation {
        // 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 {
            SpeechTranslationConfig speechTranslationConfig = SpeechTranslationConfig.fromSubscription(speechKey, speechRegion);
            speechTranslationConfig.setSpeechRecognitionLanguage("en-US");
    
            String[] toLanguages = { "it" };
            for (String language : toLanguages) {
                speechTranslationConfig.addTargetLanguage(language);
            }
    
            recognizeFromMicrophone(speechTranslationConfig);
        }
    
        public static void recognizeFromMicrophone(SpeechTranslationConfig speechTranslationConfig) throws InterruptedException, ExecutionException {
            AudioConfig audioConfig = AudioConfig.fromDefaultMicrophoneInput();
            TranslationRecognizer translationRecognizer = new TranslationRecognizer(speechTranslationConfig, audioConfig);
    
            System.out.println("Speak into your microphone.");
            Future<TranslationRecognitionResult> task = translationRecognizer.recognizeOnceAsync();
            TranslationRecognitionResult translationRecognitionResult = task.get();
    
            if (translationRecognitionResult.getReason() == ResultReason.TranslatedSpeech) {
                System.out.println("RECOGNIZED: Text=" + translationRecognitionResult.getText());
                for (Map.Entry<String, String> pair : translationRecognitionResult.getTranslations().entrySet()) {
                    System.out.printf("Translated into '%s': %s\n", pair.getKey(), pair.getValue());
                }
            }
            else if (translationRecognitionResult.getReason() == ResultReason.NoMatch) {
                System.out.println("NOMATCH: Speech could not be recognized.");
            }
            else if (translationRecognitionResult.getReason() == ResultReason.Canceled) {
                CancellationDetails cancellation = CancellationDetails.fromResult(translationRecognitionResult);
                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. 若要更改翻译目标语言,请将 it 替换为其他支持的语言。 除了少数例外,只需指定区域设置短划线 (-) 分隔符之前的语言代码。 例如,对于西班牙语(西班牙)使用 es(而不是 es-ES)。 如果未指定语言,则默认语言为 en

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

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

当系统提示时,对着麦克风说话。 你所说的内容应以目标语言的翻译文本形式输出:

Speak into your microphone.
RECOGNIZED: Text=I'm excited to try speech translation.
Translated into 'it': Sono entusiasta di provare la traduzione vocale.

注解

你现已完成快速入门,下面是一些其他注意事项:

  • 此示例使用 RecognizeOnceAsync 操作听录 30 秒以内的语音,或直到检测到静音。
  • 若要从音频文件中识别语音,请使用 fromWavFileInput,不要使用 fromDefaultMicrophoneInput
    AudioConfig audioConfig = AudioConfig.fromWavFileInput("YourAudioFile.wav");
    
  • 对于压缩的音频文件(如 MP4),请安装 GStreamer 并使用 PullAudioInputStreamPushAudioInputStream。 有关详细信息,请参阅如何使用压缩的输入音频

清理资源

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

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

在本快速入门中,你将运行一个应用程序将一种语言的语音翻译成另一种语言的文本。

先决条件

设置环境

需要先安装适用于 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. 在需要新项目的地方打开命令提示符,并创建名为 SpeechTranslation.js 的新文件。

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

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

    const fs = require("fs");
    const sdk = require("microsoft-cognitiveservices-speech-sdk");
    
    // This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
    const speechTranslationConfig = sdk.SpeechTranslationConfig.fromSubscription(process.env.SPEECH_KEY, process.env.SPEECH_REGION);
    speechTranslationConfig.speechRecognitionLanguage = "en-US";
    
    var language = "it";
    speechTranslationConfig.addTargetLanguage(language);
    
    function fromFile() {
        let audioConfig = sdk.AudioConfig.fromWavFileInput(fs.readFileSync("YourAudioFile.wav"));
        let translationRecognizer = new sdk.TranslationRecognizer(speechTranslationConfig, audioConfig);
    
        translationRecognizer.recognizeOnceAsync(result => {
            switch (result.reason) {
                case sdk.ResultReason.TranslatedSpeech:
                    console.log(`RECOGNIZED: Text=${result.text}`);
                    console.log("Translated into [" + language + "]: " + result.translations.get(language));
    
                    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;
            }
            translationRecognizer.close();
        });
    }
    fromFile();
    
  4. SpeechTranslation.js 中,将 YourAudioFile.wav 替换为你自己的 WAV 文件。 此示例仅识别 WAV 文件中的语音。 有关其他音频格式的信息,请参阅如何使用压缩的输入音频。 此示例支持最多 30 秒的音频。

  5. 若要更改语音识别语言,请将 en-US 替换为其他支持的语言。 使用短划线 (-) 分隔符指定完整的区域设置。 例如,es-ES 代表西班牙语(西班牙)。 如果未指定语言,则默认语言为 en-US。 若要详细了解如何从多种使用的语言中进行识别,请参阅语言识别

  6. 若要更改翻译目标语言,请将 it 替换为其他支持的语言。 除了少数例外,只需指定区域设置短划线 (-) 分隔符之前的语言代码。 例如,对于西班牙语(西班牙)使用 es(而不是 es-ES)。 如果未指定语言,则默认语言为 en

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

node.exe SpeechTranslation.js

音频文件中的语音应以目标语言的翻译文本形式输出:

RECOGNIZED: Text=I'm excited to try speech translation.
Translated into [it]: Sono entusiasta di provare la traduzione vocale.

注解

你现已完成快速入门,下面是一些其他注意事项:

此示例使用 recognizeOnceAsync 操作听录 30 秒以内的语音,或直到检测到静音。

备注

Node.js 中不支持识别来自麦克风的语音。 仅在基于浏览器的 JavaScript 环境中支持该功能。

清理资源

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

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

适用于 Objective-C 的语音 SDK 确实支持语音翻译,但我们尚未在此处提供相关指南。 请选择其他编程语言开始了解相关概念,或参阅本文开头链接的 Objective-C 引用和示例。

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

适用于 Swift 的语音 SDK 确实支持语音翻译,但我们尚未在此处提供相关指南。 请选择其他编程语言开始了解相关概念,或参阅本文开头链接的 Swift 引用和示例。

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

在本快速入门中,你将运行一个应用程序将一种语言的语音翻译成另一种语言的文本。

先决条件

设置环境

适用于 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_translation.py 的新文件。

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

    pip install azure-cognitiveservices-speech
    
  3. 将以下代码复制到 speech_translation.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_translation_config = speechsdk.translation.SpeechTranslationConfig(subscription=os.environ.get('SPEECH_KEY'), region=os.environ.get('SPEECH_REGION'))
        speech_translation_config.speech_recognition_language="en-US"
    
        target_language="it"
        speech_translation_config.add_target_language(target_language)
    
        audio_config = speechsdk.audio.AudioConfig(use_default_microphone=True)
        translation_recognizer = speechsdk.translation.TranslationRecognizer(translation_config=speech_translation_config, audio_config=audio_config)
    
        print("Speak into your microphone.")
        translation_recognition_result = translation_recognizer.recognize_once_async().get()
    
        if translation_recognition_result.reason == speechsdk.ResultReason.TranslatedSpeech:
            print("Recognized: {}".format(translation_recognition_result.text))
            print("""Translated into '{}': {}""".format(
                target_language, 
                translation_recognition_result.translations[target_language]))
        elif translation_recognition_result.reason == speechsdk.ResultReason.NoMatch:
            print("No speech could be recognized: {}".format(translation_recognition_result.no_match_details))
        elif translation_recognition_result.reason == speechsdk.ResultReason.Canceled:
            cancellation_details = translation_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. 若要更改翻译目标语言,请将 it 替换为其他支持的语言。 除了少数例外,只需指定区域设置短划线 (-) 分隔符之前的语言代码。 例如,对于西班牙语(西班牙)使用 es(而不是 es-ES)。 如果未指定语言,则默认语言为 en

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

python speech_translation.py

当系统提示时,对着麦克风说话。 你所说的内容应以目标语言的翻译文本形式输出:

Speak into your microphone.
Recognized: I'm excited to try speech translation.
Translated into 'it': Sono entusiasta di provare la traduzione vocale.

注解

你现已完成快速入门,下面是一些其他注意事项:

  • 此示例使用 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 的其他示例

REST API 不支持语音翻译。 请从此页顶部选择其他编程语言或工具。

在本快速入门中,你将运行一个应用程序将一种语言的语音翻译成另一种语言的文本。

先决条件

设置环境

请按照以下步骤操作,并参阅语音 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
    

翻译来自麦克风的语音

运行以下命令将麦克风中的语音从英语翻译为意大利语:

spx translate --source en-US --target it --microphone

对着麦克风说话,并实时看到翻译后的语音转录。 如果停止说话一段时间(30 秒),或者按下 Ctrl+C,语音 CLI 将停止。

Connection CONNECTED...
TRANSLATING into 'it': Sono (from 'I'm')
TRANSLATING into 'it': Sono entusiasta (from 'I'm excited to')
TRANSLATING into 'it': Sono entusiasta di provare la parola (from 'I'm excited to try speech')
TRANSLATED into 'it': Sono entusiasta di provare la traduzione vocale. (from 'I'm excited to try speech translation.')

备注

完成快速入门后,下面是一些其他注意事项:

  • 若要获取音频文件中的语音,请使用 --file 而不是 --microphone。 对于压缩的音频文件(如 MP4),请安装 GStreamer 并使用 --format。 有关详细信息,请参阅如何使用压缩的输入音频
    spx translate --source en-US --target it --file YourAudioFile.wav
    spx translate --source en-US --target it --file YourAudioFile.mp4 --format any
    
  • 若要提高特定字词或语句的识别准确性,请使用短语列表。 你可以在行中包含短语列表,也可以使用文本文件:
    spx translate --source en-US --target it --microphone --phrases "Contoso;Jessie;Rehaan;"
    spx translate --source en-US --target it --microphone --phrases @phrases.txt
    
  • 若要更改语音识别语言,请将 en-US 替换为其他支持的语言。 使用短划线 (-) 分隔符指定完整的区域设置。 例如,es-ES 代表西班牙语(西班牙)。 如果未指定语言,则默认语言为 en-US
    spx translate --microphone --source es-ES
    
  • 若要更改翻译目标语言,请将 it 替换为其他支持的语言。 除了少数例外,只需指定区域设置短划线 (-) 分隔符之前的语言代码。 例如,对于西班牙语(西班牙)使用 es(而不是 es-ES)。 如果未指定语言,则默认语言为 en
    spx translate --microphone --target es
    
  • 对于 30 秒以上的连续音频识别,请追加 --continuous
    spx translate --source en-US --target it --microphone --continuous
    

运行以下命令,了解更多有关语音翻译选项的信息,例如文件输入和输出:

spx help translate

清理资源

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