了解语音翻译基础知识Learn the basics of speech translation

语音服务的核心功能之一是能够识别人类语音并将其翻译成其他语言。One of the core features of the Speech service is the ability to recognize human speech and translate it to other languages. 本文介绍如何在应用和产品中使用语音 SDK 来执行高质量的语音翻译。In this article you'll learn how to use the Speech SDK in your apps and products to perform high-quality speech translation.

提示

如果你没有机会完成我们的快速入门之一,我们建议你在购买之前仔细检查,并自行试用语音翻译。If you haven't had a chance to complete one of our quickstarts, we encourage you to kick the tires and try speech translation out for yourself.

先决条件Prerequisites

本文假设已有一个 Azure 帐户和语音服务订阅。This article assumes that you have an Azure account and Speech service subscription. 如果你没有帐户和订阅,可免费试用语音服务If you don't have an account and subscription, try the Speech service for free.

安装语音 SDKInstall the Speech SDK

需要先安装语音 SDK,然后才能执行任何操作。Before you can do anything, you'll need to install the Speech SDK. 根据你的平台,按照“语音 SDK”一文的获取语音 SDK 部分中的说明进行操作。Depending on your platform, follow the instructions under the Get the Speech SDK section of the Speech SDK article.

导入依赖项Import dependencies

若要运行本文中的示例,请在 Program.cs 文件的顶部添加以下 using 语句。To run the examples in this article, include the following using statements at the top of the Program.cs file.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using Microsoft.CognitiveServices.Speech.Translation;

敏感数据和环境变量Sensitive data and environment variables

本文中的示例源代码依赖于用于存储敏感数据的环境变量,如语音资源订阅密钥和区域。The example source code in this article depends on environment variables for storing sensitive data, such as the Speech resource subscription key and region. Program 类包含从主机环境变量(即 SPEECH__SUBSCRIPTION__KEYSPEECH__SERVICE__REGION)分配的两个 static readonly string 值。The Program class contains two static readonly string values that are assigned from the host machines environment variables, namely SPEECH__SUBSCRIPTION__KEY and SPEECH__SERVICE__REGION. 这两个字段都在类范围内,因此可以在类的方法主体中访问它们。Both of these fields are at the class scope, making them accessible within method bodies of the class.

public class Program
{
    static readonly string SPEECH__SUBSCRIPTION__KEY =
        Environment.GetEnvironmentVariable(nameof(SPEECH__SUBSCRIPTION__KEY));
    
    static readonly string SPEECH__SERVICE__REGION =
        Environment.GetEnvironmentVariable(nameof(SPEECH__SERVICE__REGION));

    static Task Main() => Task.CompletedTask;
}

创建语音翻译配置Create a speech translation configuration

若要使用语音 SDK 调用语音服务,需要创建 SpeechTranslationConfigTo call the Speech service using the Speech SDK, you need to create a SpeechTranslationConfig. 此类包含有关订阅的信息,例如密钥和关联的区域、终结点、主机或授权令牌。This class includes information about your subscription, like your key and associated region, endpoint, host, or authorization token.

提示

无论是要执行语音识别、语音合成、翻译还是意向识别,都需要创建一个配置。Regardless of whether you're performing speech recognition, speech synthesis, translation, or intent recognition, you'll always create a configuration.

可以通过以下几种方法初始化 SpeechTranslationConfigThere are a few ways that you can initialize a SpeechTranslationConfig:

  • 使用订阅:传入密钥和关联的区域。With a subscription: pass in a key and the associated region.
  • 使用终结点:传入语音服务终结点。With an endpoint: pass in a Speech service endpoint. 密钥或授权令牌是可选的。A key or authorization token is optional.
  • 使用主机:传入主机地址。With a host: pass in a host address. 密钥或授权令牌是可选的。A key or authorization token is optional.
  • 使用授权令牌:传入授权令牌和关联的区域。With an authorization token: pass in an authorization token and the associated region.

让我们看看如何使用密钥和区域创建 SpeechTranslationConfigLet's take a look at how a SpeechTranslationConfig is created using a key and region. 请查看区域支持页,找到你的区域标识符。See the region support page to find your region identifier.

public class Program
{
    static readonly string SPEECH__SUBSCRIPTION__KEY =
        Environment.GetEnvironmentVariable(nameof(SPEECH__SUBSCRIPTION__KEY));
    
    static readonly string SPEECH__SERVICE__REGION =
        Environment.GetEnvironmentVariable(nameof(SPEECH__SERVICE__REGION));

    static Task Main() => TranslateSpeechAsync();

    static async Task TranslateSpeechAsync()
    {
        var translationConfig =
            SpeechTranslationConfig.FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    }
}

更改源语言Change source language

语音翻译的一项常见任务是指定输入(或源)语言。One common task of speech translation is specifying the input (or source) language. 让我们看看如何将输入语言更改为意大利语。Let's take a look at how you would change the input language to Italian. 在代码中与 SpeechTranslationConfig 实例交互,为 SpeechRecognitionLanguage 属性赋值。In your code, interact with the SpeechTranslationConfig instance, assigning to the SpeechRecognitionLanguage property.

static async Task TranslateSpeechAsync()
{
    var translationConfig =
        SpeechTranslationConfig.FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);

    // Source (input) language
    translationConfig.SpeechRecognitionLanguage = "ko-KR";
}

SpeechRecognitionLanguage 属性需要语言区域设置格式字符串。The SpeechRecognitionLanguage property expects a language-locale format string. 可以提供受支持的区域设置/语言的列表中“区域设置”列中的任何值 。You can provide any value in the Locale column in the list of supported locales/languages.

添加翻译语言Add translation language

语音翻译的另一项常见任务是指定目标翻译语言,至少需要一种语言,但支持多种语言。Another common task of speech translation is to specify target translation languages, at least one is required but multiples are supported. 在以下代码片段中,法语和德语都作为目标翻译语言。In the following code snippet, both French and German as translation language targets.

static async Task TranslateSpeechAsync()
{
    var translationConfig =
        SpeechTranslationConfig.FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);

    translationConfig.SpeechRecognitionLanguage = "ko-KR";
    
    // Translate to languages. See, https://aka.ms/speech/sttt-languages
    translationConfig.AddTargetLanguage("fr");
    translationConfig.AddTargetLanguage("de");
}

每次调用 AddTargetLanguage 时,都会指定一种新的目标翻译语言。With every call to AddTargetLanguage, a new target translation language is specified. 换言之,根据源语言识别语音后,就会在接着进行的翻译操作过程中提供每项目标翻译。In other words, when speech is recognized from the source language, each target translation is available as part of the resulting translation operation.

初始化翻译识别器Initialize a translation recognizer

创建 SpeechTranslationConfig 后,下一步是初始化 TranslationRecognizerAfter you've created a SpeechTranslationConfig, the next step is to initialize a TranslationRecognizer. 初始化 TranslationRecognizer 时,需要向其传递 translationConfigWhen you initialize a TranslationRecognizer, you'll need to pass it your translationConfig. 配置对象会提供验证你的请求时语音服务所需的凭据。The configuration object provides the credentials that the speech service requires to validate your request.

如果使用设备的默认麦克风识别语音,则 TranslationRecognizer 应如下所示:If you're recognizing speech using your device's default microphone, here's what the TranslationRecognizer should look like:

static async Task TranslateSpeechAsync()
{
    var translationConfig =
        SpeechTranslationConfig.FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);

    var fromLanguage = "en-US";
    var toLanguages = new List<string> { "ko", "fr", "de" };
    translationConfig.SpeechRecognitionLanguage = fromLanguage;
    toLanguages.ForEach(translationConfig.AddTargetLanguage);

    using var recognizer = new TranslationRecognizer(translationConfig);
}

如果要指定音频输入设备,则需要创建一个 AudioConfig 并在初始化 TranslationRecognizer 时提供 audioConfig 参数。If you want to specify the audio input device, then you'll need to create an AudioConfig and provide the audioConfig parameter when initializing your TranslationRecognizer.

首先,引用 AudioConfig 对象,如下所示:First, you'll reference the AudioConfig object as follows:

static async Task TranslateSpeechAsync()
{
    var translationConfig =
        SpeechTranslationConfig.FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    
    var fromLanguage = "en-US";
    var toLanguages = new List<string> { "ko", "fr", "de" };
    translationConfig.SpeechRecognitionLanguage = fromLanguage;
    toLanguages.ForEach(translationConfig.AddTargetLanguage);

    using var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
    using var recognizer = new TranslationRecognizer(translationConfig, audioConfig);
}

如果要提供音频文件而不是使用麦克风,则仍需要提供 audioConfigIf you want to provide an audio file instead of using a microphone, you'll still need to provide an audioConfig. 但是,在创建 AudioConfig(而不是调用 FromDefaultMicrophoneInput)时,将调用 FromWavFileInput 并传递 filename 参数。However, when you create an AudioConfig, instead of calling FromDefaultMicrophoneInput, you'll call FromWavFileInput and pass the filename parameter.

static async Task TranslateSpeechAsync()
{
    var translationConfig =
        SpeechTranslationConfig.FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    
    var fromLanguage = "en-US";
    var toLanguages = new List<string> { "ko", "fr", "de" };
    translationConfig.SpeechRecognitionLanguage = fromLanguage;
    toLanguages.ForEach(translationConfig.AddTargetLanguage);

    using var audioConfig = AudioConfig.FromWavFileInput("YourAudioFile.wav");
    using var recognizer = new TranslationRecognizer(translationConfig, audioConfig);
}

翻译语音Translate speech

为了翻译语音,语音 SDK 依赖于麦克风或音频文件输入。To translate speech, the Speech SDK relies on a microphone or an audio file input. 在语音翻译之前先进行语音识别。Speech recognition occurs before speech translation. 初始化所有对象后,调用识别一次的函数并获取结果。After all objects have been initialized, call the recognize-once function and get the result.

static async Task TranslateSpeechAsync()
{
    var translationConfig =
        SpeechTranslationConfig.FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    
    var fromLanguage = "en-US";
    var toLanguages = new List<string> { "ko", "fr", "de" };
    translationConfig.SpeechRecognitionLanguage = fromLanguage;
    toLanguages.ForEach(translationConfig.AddTargetLanguage);

    using var recognizer = new TranslationRecognizer(translationConfig);

    Console.Write($"Say something in '{fromLanguage}' and ");
    Console.WriteLine($"we'll translate into '{string.Join("', '", toLanguages)}'.\n");
    
    var result = await recognizer.RecognizeOnceAsync();
    if (result.Reason == ResultReason.TranslatedSpeech)
    {
        Console.WriteLine($"Recognized: \"{result.Text}\":");
        foreach (var (language, translation) in result.Translations)
        {
            Console.WriteLine($"Translated into '{language}': {translation}");
        }
    }
}

有关语音转文本的详细信息,请参阅语音识别基础知识For more information about speech-to-text, see the basics of speech recognition.

合成翻译Synthesize translations

成功进行语音识别和翻译后,结果会包含字典中的所有翻译。After a successful speech recognition and translation, the result contains all the translations in a dictionary. Translations 字典键是目标翻译语言,其值是已翻译的文本。The Translations dictionary key is the target translation language and the value is the translated text. 可以翻译已识别的语音,然后以另一种语言进行合成(语音转语音)。Recognized speech can be translated, then synthesized in a different language (speech-to-speech).

基于事件的合成Event-based synthesis

TranslationRecognizer 对象公开了 Synthesizing 事件。The TranslationRecognizer object exposes a Synthesizing event. 该事件触发多次,并提供一种从翻译识别结果检索合成音频的机制。The event fires several times, and provides a mechanism to retrieve the synthesized audio from the translation recognition result. 若要翻译为多种语言,请参阅手动合成If you're translating to multiple languages, see manual synthesis. 通过分配 VoiceName 指定合成语音,并为 Synthesizing 事件提供事件处理程序,获取音频。Specify the synthesis voice by assigning a VoiceName and provide an event handler for the Synthesizing event, get the audio. 以下示例将已翻译的音频另存为 .wav 文件。The following example saves the translated audio as a .wav file.

重要

基于事件的合成仅适用于单项翻译,请勿 添加多种目标翻译语言。The event-based synthesis only works with a single translation, do not add multiple target translation languages. 此外,VoiceName 应与目标翻译语言相同(例如,"de" 可映射到 "de-DE-Hedda")。Additionally, the VoiceName should be the same language as the target translation language, for example; "de" could map to "de-DE-Hedda".

static async Task TranslateSpeechAsync()
{
    var translationConfig =
        SpeechTranslationConfig.FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    
    var fromLanguage = "en-US";
    var toLanguage = "de";
    translationConfig.SpeechRecognitionLanguage = fromLanguage;
    translationConfig.AddTargetLanguage(toLanguage);

    // See: https://aka.ms/speech/sdkregion#standard-and-neural-voices
    translationConfig.VoiceName = "de-DE-Hedda";

    using var recognizer = new TranslationRecognizer(translationConfig);

    recognizer.Synthesizing += (_, e) =>
    {
        var audio = e.Result.GetAudio();
        Console.WriteLine($"Audio synthesized: {audio.Length:#,0} byte(s) {(audio.Length == 0 ? "(Complete)" : "")}");

        if (audio.Length > 0)
        {
            File.WriteAllBytes("YourAudioFile.wav", audio);
        }
    };

    Console.Write($"Say something in '{fromLanguage}' and ");
    Console.WriteLine($"we'll translate into '{toLanguage}'.\n");

    var result = await recognizer.RecognizeOnceAsync();
    if (result.Reason == ResultReason.TranslatedSpeech)
    {
        Console.WriteLine($"Recognized: \"{result.Text}\"");
        Console.WriteLine($"Translated into '{toLanguage}': {result.Translations[toLanguage]}");
    }
}

手动合成Manual synthesis

Translations 字典可用于从翻译文本合成音频。The Translations dictionary can be used to synthesize audio from the translation text. 循环访问每项翻译,并合成翻译。Iterate through each translation, and synthesize the translation. 创建 SpeechSynthesizer 实例时,SpeechConfig 对象需要将其 SpeechSynthesisVoiceName 属性设为所需的语音。When creating a SpeechSynthesizer instance, the SpeechConfig object needs to have its SpeechSynthesisVoiceName property set to the desired voice. 以下示例翻译为五种语言,然后将每种翻译合成为相应神经语言的音频文件。The following example translates to five languages, and each translation is then synthesized to an audio file in the corresponding neural language.

static async Task TranslateSpeechAsync()
{
    var translationConfig =
        SpeechTranslationConfig.FromSubscription(SPEECH__SERVICE__KEY, SPEECH__SERVICE__REGION);

    var fromLanguage = "en-US";
    var toLanguages = new List<string> { "de", "en", "zh-Hans" };
    translationConfig.SpeechRecognitionLanguage = fromLanguage;
    toLanguages.ForEach(translationConfig.AddTargetLanguage);

    using var recognizer = new TranslationRecognizer(translationConfig);

    Console.Write($"Say something in '{fromLanguage}' and ");
    Console.WriteLine($"we'll translate into '{string.Join("', '", toLanguages)}'.\n");

    var result = await recognizer.RecognizeOnceAsync();
    if (result.Reason == ResultReason.TranslatedSpeech)
    {
        // See: https://aka.ms/speech/sdkregion#standard-and-neural-voices
        var languageToVoiceMap = new Dictionary<string, string>
        {
            ["de"] = "de-DE-KatjaNeural",
            ["en"] = "en-US-AriaNeural",
            ["zh-Hans"] = "zh-CN-XiaoxiaoNeural"
        };

        Console.WriteLine($"Recognized: \"{result.Text}\"");

        foreach (var (language, translation) in result.Translations)
        {
            Console.WriteLine($"Translated into '{language}': {translation}");

            var speechConfig =
                SpeechConfig.FromSubscription(
                    SPEECH__SERVICE__KEY, SPEECH__SERVICE__REGION);
            speechConfig.SpeechSynthesisVoiceName = languageToVoiceMap[language];

            using var audioConfig = AudioConfig.FromWavFileOutput($"{language}-translation.wav");
            using var synthesizer = new SpeechSynthesizer(speechConfig, audioConfig);
            
            await synthesizer.SpeakTextAsync(translation);
        }
    }
}

有关语音合成的详细信息,请参阅语音合成基础知识For more information about speech synthesis, see the basics of speech synthesis.

先决条件Prerequisites

本文假设已有一个 Azure 帐户和语音服务订阅。This article assumes that you have an Azure account and Speech service subscription. 如果你没有帐户和订阅,可免费试用语音服务If you don't have an account and subscription, try the Speech service for free.

安装语音 SDKInstall the Speech SDK

需要先安装语音 SDK,然后才能执行任何操作。Before you can do anything, you'll need to install the Speech SDK. 根据你的平台,按照“语音 SDK”一文的获取语音 SDK 部分中的说明进行操作。Depending on your platform, follow the instructions under the Get the Speech SDK section of the Speech SDK article.

导入依赖项Import dependencies

若要运行本文中的示例,请在 C++ 代码文件的顶部包含以下 #includeusing 语句。To run the examples in this article, include the following #include and using statements at the top of the C++ code file.

#include <iostream> // cin, cout
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <speechapi_cxx.h>

using namespace std;
using namespace Microsoft::CognitiveServices::Speech;
using namespace Microsoft::CognitiveServices::Speech::Audio;
using namespace Microsoft::CognitiveServices::Speech::Translation;

敏感数据和环境变量Sensitive data and environment variables

本文中的示例源代码依赖于用于存储敏感数据的环境变量,如语音资源订阅密钥和区域。The example source code in this article depends on environment variables for storing sensitive data, such as the Speech resource subscription key and region. C++ 代码文件包含从主机环境变量(即 SPEECH__SUBSCRIPTION__KEYSPEECH__SERVICE__REGION)分配的两个字符串值。The C++ code file contains two string values that are assigned from the host machines environment variables, namely SPEECH__SUBSCRIPTION__KEY and SPEECH__SERVICE__REGION. 这两个字段都在类范围内,因此可以在类的方法主体中访问它们。Both of these fields are at the class scope, making them accessible within method bodies of the class.

auto SPEECH__SUBSCRIPTION__KEY = getenv("SPEECH__SUBSCRIPTION__KEY");
auto SPEECH__SERVICE__REGION = getenv("SPEECH__SERVICE__REGION");

创建语音翻译配置Create a speech translation configuration

若要使用语音 SDK 调用语音服务,需要创建 SpeechTranslationConfigTo call the Speech service using the Speech SDK, you need to create a SpeechTranslationConfig. 此类包含有关订阅的信息,例如密钥和关联的区域、终结点、主机或授权令牌。This class includes information about your subscription, like your key and associated region, endpoint, host, or authorization token.

提示

无论是要执行语音识别、语音合成还是翻译,都需要创建一个配置。Regardless of whether you're performing speech recognition, speech synthesis or translation, you'll always create a configuration.

可以通过以下几种方法初始化 SpeechTranslationConfigThere are a few ways that you can initialize a SpeechTranslationConfig:

  • 使用订阅:传入密钥和关联的区域。With a subscription: pass in a key and the associated region.
  • 使用终结点:传入语音服务终结点。With an endpoint: pass in a Speech service endpoint. 密钥或授权令牌是可选的。A key or authorization token is optional.
  • 使用主机:传入主机地址。With a host: pass in a host address. 密钥或授权令牌是可选的。A key or authorization token is optional.
  • 使用授权令牌:传入授权令牌和关联的区域。With an authorization token: pass in an authorization token and the associated region.

让我们看看如何使用密钥和区域创建 SpeechTranslationConfigLet's take a look at how a SpeechTranslationConfig is created using a key and region. 请查看区域支持页,找到你的区域标识符。See the region support page to find your region identifier.

auto SPEECH__SUBSCRIPTION__KEY = getenv("SPEECH__SUBSCRIPTION__KEY");
auto SPEECH__SERVICE__REGION = getenv("SPEECH__SERVICE__REGION");

void translateSpeech() {
    auto config =
        SpeechTranslationConfig::FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
}

int main(int argc, char** argv) {
    setlocale(LC_ALL, "");
    translateSpeech();
    return 0;
}

更改源语言Change source language

语音翻译的一项常见任务是指定输入(或源)语言。One common task of speech translation is specifying the input (or source) language. 让我们看看如何将输入语言更改为意大利语。Let's take a look at how you would change the input language to Italian. 在代码中与 SpeechTranslationConfig 实例交互,调用 SetSpeechRecognitionLanguage 方法。In your code, interact with the SpeechTranslationConfig instance, calling the SetSpeechRecognitionLanguage method.

void translateSpeech() {
    auto translationConfig =
        SpeechTranslationConfig::FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);

    // Source (input) language
    translationConfig->SetSpeechRecognitionLanguage("it-IT");
}

SpeechRecognitionLanguage 属性需要语言区域设置格式字符串。The SpeechRecognitionLanguage property expects a language-locale format string. 可以提供受支持的区域设置/语言的列表中“区域设置”列中的任何值 。You can provide any value in the Locale column in the list of supported locales/languages.

添加翻译语言Add translation language

语音翻译的另一项常见任务是指定目标翻译语言,至少需要一种语言,但支持多种语言。Another common task of speech translation is to specify target translation languages, at least one is required but multiples are supported. 在以下代码片段中,法语和德语都作为目标翻译语言。In the following code snippet, both French and German as translation language targets.

void translateSpeech() {
    auto translationConfig =
        SpeechTranslationConfig::FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);

    translationConfig->SetSpeechRecognitionLanguage("ko-KR");

    // Translate to languages. See, https://aka.ms/speech/sttt-languages
    translationConfig->AddTargetLanguage("fr");
    translationConfig->AddTargetLanguage("de");
}

每次调用 AddTargetLanguage 时,都会指定一种新的目标翻译语言。With every call to AddTargetLanguage, a new target translation language is specified. 换言之,根据源语言识别语音后,就会在接着进行的翻译操作过程中提供每项目标翻译。In other words, when speech is recognized from the source language, each target translation is available as part of the resulting translation operation.

初始化翻译识别器Initialize a translation recognizer

创建 SpeechTranslationConfig 后,下一步是初始化 TranslationRecognizerAfter you've created a SpeechTranslationConfig, the next step is to initialize a TranslationRecognizer. 初始化 TranslationRecognizer 时,需要向其传递 translationConfigWhen you initialize a TranslationRecognizer, you'll need to pass it your translationConfig. 配置对象会提供验证你的请求时语音服务所需的凭据。The configuration object provides the credentials that the speech service requires to validate your request.

如果使用设备的默认麦克风识别语音,则 TranslationRecognizer 应如下所示:If you're recognizing speech using your device's default microphone, here's what the TranslationRecognizer should look like:

void translateSpeech() {
    auto translationConfig =
        SpeechTranslationConfig::FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);

    auto fromLanguage = "en-US";
    auto toLanguages = { "ko", "fr", "de" };
    translationConfig->SetSpeechRecognitionLanguage(fromLanguage);
    for (auto language : toLanguages) {
        translationConfig->AddTargetLanguage(language);
    }

    auto recognizer = TranslationRecognizer::FromConfig(translationConfig);
}

如果要指定音频输入设备,则需要创建一个 AudioConfig 并在初始化 TranslationRecognizer 时提供 audioConfig 参数。If you want to specify the audio input device, then you'll need to create an AudioConfig and provide the audioConfig parameter when initializing your TranslationRecognizer.

首先,引用 AudioConfig 对象,如下所示:First, you'll reference the AudioConfig object as follows:

void translateSpeech() {
    auto translationConfig =
        SpeechTranslationConfig::FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);

    auto fromLanguage = "en-US";
    auto toLanguages = { "ko", "fr", "de" };
    translationConfig->SetSpeechRecognitionLanguage(fromLanguage);
    for (auto language : toLanguages) {
        translationConfig->AddTargetLanguage(language);
    }

    auto audioConfig = AudioConfig::FromDefaultMicrophoneInput();
    auto recognizer = TranslationRecognizer::FromConfig(translationConfig, audioConfig);
}

如果要提供音频文件而不是使用麦克风,则仍需要提供 audioConfigIf you want to provide an audio file instead of using a microphone, you'll still need to provide an audioConfig. 但是,在创建 AudioConfig(而不是调用 FromDefaultMicrophoneInput)时,将调用 FromWavFileInput 并传递 filename 参数。However, when you create an AudioConfig, instead of calling FromDefaultMicrophoneInput, you'll call FromWavFileInput and pass the filename parameter.

void translateSpeech() {
    auto translationConfig =
        SpeechTranslationConfig::FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);

    auto fromLanguage = "en-US";
    auto toLanguages = { "ko", "fr", "de" };
    translationConfig->SetSpeechRecognitionLanguage(fromLanguage);
    for (auto language : toLanguages) {
        translationConfig->AddTargetLanguage(language);
    }

    auto audioConfig = AudioConfig::FromWavFileInput("YourAudioFile.wav");
    auto recognizer = TranslationRecognizer::FromConfig(translationConfig, audioConfig);
}

翻译语音Translate speech

为了翻译语音,语音 SDK 依赖于麦克风或音频文件输入。To translate speech, the Speech SDK relies on a microphone or an audio file input. 在语音翻译之前先进行语音识别。Speech recognition occurs before speech translation. 初始化所有对象后,调用识别一次的函数并获取结果。After all objects have been initialized, call the recognize-once function and get the result.

void translateSpeech() {
    auto translationConfig =
        SpeechTranslationConfig::FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);

    string fromLanguage = "en-US";
    string toLanguages[3] = { "ko", "fr", "de" };
    translationConfig->SetSpeechRecognitionLanguage(fromLanguage);
    for (auto language : toLanguages) {
        translationConfig->AddTargetLanguage(language);
    }

    auto recognizer = TranslationRecognizer::FromConfig(translationConfig);
    cout << "Say something in '" << fromLanguage << "' and we'll translate...\n";

    auto result = recognizer->RecognizeOnceAsync().get();
    if (result->Reason == ResultReason::TranslatedSpeech)
    {
        cout << "Recognized: \"" << result->Text << "\"" << std::endl;
        for (auto pair : result->Translations)
        {
            auto language = pair.first;
            auto translation = pair.second;
            cout << "Translated into '" << language << "': " << translation << std::endl;
        }
    }
}

有关语音转文本的详细信息,请参阅语音识别基础知识For more information about speech-to-text, see the basics of speech recognition.

合成翻译Synthesize translations

成功进行语音识别和翻译后,结果会包含字典中的所有翻译。After a successful speech recognition and translation, the result contains all the translations in a dictionary. Translations 字典键是目标翻译语言,其值是已翻译的文本。The Translations dictionary key is the target translation language and the value is the translated text. 可以翻译已识别的语音,然后以另一种语言进行合成(语音转语音)。Recognized speech can be translated, then synthesized in a different language (speech-to-speech).

基于事件的合成Event-based synthesis

TranslationRecognizer 对象公开了 Synthesizing 事件。The TranslationRecognizer object exposes a Synthesizing event. 该事件触发多次,并提供一种从翻译识别结果检索合成音频的机制。The event fires several times, and provides a mechanism to retrieve the synthesized audio from the translation recognition result. 若要翻译为多种语言,请参阅手动合成If you're translating to multiple languages, see manual synthesis. 通过分配 SetVoiceName 指定合成语音,并为 Synthesizing 事件提供事件处理程序,获取音频。Specify the synthesis voice by assigning a SetVoiceName and provide an event handler for the Synthesizing event, get the audio. 以下示例将已翻译的音频另存为 .wav 文件。The following example saves the translated audio as a .wav file.

重要

基于事件的合成仅适用于单项翻译,请勿 添加多种目标翻译语言。The event-based synthesis only works with a single translation, do not add multiple target translation languages. 此外,SetVoiceName 应与目标翻译语言相同(例如,"de" 可映射到 "de-DE-Hedda")。Additionally, the SetVoiceName should be the same language as the target translation language, for example; "de" could map to "de-DE-Hedda".

void translateSpeech() {
    auto translationConfig =
        SpeechTranslationConfig::FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);

    auto fromLanguage = "en-US";
    auto toLanguage = "de";
    translationConfig->SetSpeechRecognitionLanguage(fromLanguage);
    translationConfig->AddTargetLanguage(toLanguage);

    // See: https://aka.ms/speech/sdkregion#standard-and-neural-voices
    translationConfig->SetVoiceName("de-DE-Hedda");

    auto recognizer = TranslationRecognizer::FromConfig(translationConfig);
    recognizer->Synthesizing.Connect([](const TranslationSynthesisEventArgs& e)
        {
            auto audio = e.Result->Audio;
            auto size = audio.size();
            cout << "Audio synthesized: " << size << " byte(s)" << (size == 0 ? "(COMPLETE)" : "") << std::endl;

            if (size > 0) {
                ofstream file("translation.wav", ios::out | ios::binary);
                auto audioData = audio.data();
                file.write((const char*)audioData, sizeof(audio[0]) * size);
                file.close();
            }
        });

    cout << "Say something in '" << fromLanguage << "' and we'll translate...\n";

    auto result = recognizer->RecognizeOnceAsync().get();
    if (result->Reason == ResultReason::TranslatedSpeech)
    {
        cout << "Recognized: \"" << result->Text << "\"" << std::endl;
        for (auto pair : result->Translations)
        {
            auto language = pair.first;
            auto translation = pair.second;
            cout << "Translated into '" << language << "': " << translation << std::endl;
        }
    }
}

手动合成Manual synthesis

Translations 字典可用于从翻译文本合成音频。The Translations dictionary can be used to synthesize audio from the translation text. 循环访问每项翻译,并合成翻译。Iterate through each translation, and synthesize the translation. 创建 SpeechSynthesizer 实例时,SpeechConfig 对象需要将其 SetSpeechSynthesisVoiceName 属性设为所需的语音。When creating a SpeechSynthesizer instance, the SpeechConfig object needs to have its SetSpeechSynthesisVoiceName property set to the desired voice. 以下示例翻译为五种语言,然后将每种翻译合成为相应神经语言的音频文件。The following example translates to five languages, and each translation is then synthesized to an audio file in the corresponding neural language.

void translateSpeech() {
    auto translationConfig =
        SpeechTranslationConfig::FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);

    auto fromLanguage = "en-US";
    auto toLanguages = { "de", "en", "zh-Hans" };
    translationConfig->SetSpeechRecognitionLanguage(fromLanguage);
    for (auto language : toLanguages) {
        translationConfig->AddTargetLanguage(language);
    }

    auto recognizer = TranslationRecognizer::FromConfig(translationConfig);

    cout << "Say something in '" << fromLanguage << "' and we'll translate...\n";

    auto result = recognizer->RecognizeOnceAsync().get();
    if (result->Reason == ResultReason::TranslatedSpeech)
    {
        // See: https://aka.ms/speech/sdkregion#standard-and-neural-voices
        map<string, string> languageToVoiceMap;
        languageToVoiceMap["de"] = "de-DE-KatjaNeural";
        languageToVoiceMap["en"] = "en-US-AriaNeural";
        languageToVoiceMap["zh-Hans"] = "zh-CN-XiaoxiaoNeural";

        cout << "Recognized: \"" << result->Text << "\"" << std::endl;
        for (auto pair : result->Translations)
        {
            auto language = pair.first;
            auto translation = pair.second;
            cout << "Translated into '" << language << "': " << translation << std::endl;

            auto speech_config =
                SpeechConfig::FromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
            speech_config->SetSpeechSynthesisVoiceName(languageToVoiceMap[language]);

            auto audio_config = AudioConfig::FromWavFileOutput(language + "-translation.wav");
            auto synthesizer = SpeechSynthesizer::FromConfig(speech_config, audio_config);

            synthesizer->SpeakTextAsync(translation).get();
        }
    }
}

有关语音合成的详细信息,请参阅语音合成基础知识For more information about speech synthesis, see the basics of speech synthesis.

先决条件Prerequisites

本文假设已有一个 Azure 帐户和语音服务订阅。This article assumes that you have an Azure account and Speech service subscription. 如果你没有帐户和订阅,可免费试用语音服务If you don't have an account and subscription, try the Speech service for free.

安装语音 SDKInstall the Speech SDK

需要先安装语音 SDK,然后才能执行任何操作。Before you can do anything, you'll need to install the Speech SDK. 根据你的平台,按照“语音 SDK”一文的获取语音 SDK 部分中的说明进行操作。Depending on your platform, follow the instructions under the Get the Speech SDK section of the Speech SDK article.

导入依赖项Import dependencies

若要运行本文中的示例,请在 *.Java 代码文件的顶部添加以下 import 语句。To run the examples in this article, include the following import statements at the top of the *.Java code file.

package speech;

import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.audio.*;
import com.microsoft.cognitiveservices.speech.translation.*;

敏感数据和环境变量Sensitive data and environment variables

本文中的示例源代码依赖于用于存储敏感数据的环境变量,如语音资源订阅密钥和区域。The example source code in this article depends on environment variables for storing sensitive data, such as the Speech resource subscription key and region. Java 代码文件包含从主机环境变量(即 SPEECH__SUBSCRIPTION__KEYSPEECH__SERVICE__REGION)分配的两个 static final String 值。The Java code file contains two static final String values that are assigned from the host machines environment variables, namely SPEECH__SUBSCRIPTION__KEY and SPEECH__SERVICE__REGION. 这两个字段都在类范围内,因此可以在类的方法主体中访问它们。Both of these fields are at the class scope, making them accessible within method bodies of the class.

public class App {

    static final String SPEECH__SUBSCRIPTION__KEY = System.getenv("SPEECH__SUBSCRIPTION__KEY");
    static final String SPEECH__SERVICE__REGION = System.getenv("SPEECH__SERVICE__REGION");

    public static void main(String[] args) { }
}

创建语音翻译配置Create a speech translation configuration

若要使用语音 SDK 调用语音服务,需要创建 SpeechTranslationConfigTo call the Speech service using the Speech SDK, you need to create a SpeechTranslationConfig. 此类包含有关订阅的信息,例如密钥和关联的区域、终结点、主机或授权令牌。This class includes information about your subscription, like your key and associated region, endpoint, host, or authorization token.

提示

无论是要执行语音识别、语音合成、翻译还是意向识别,都需要创建一个配置。Regardless of whether you're performing speech recognition, speech synthesis, translation, or intent recognition, you'll always create a configuration.

可以通过以下几种方法初始化 SpeechTranslationConfigThere are a few ways that you can initialize a SpeechTranslationConfig:

  • 使用订阅:传入密钥和关联的区域。With a subscription: pass in a key and the associated region.
  • 使用终结点:传入语音服务终结点。With an endpoint: pass in a Speech service endpoint. 密钥或授权令牌是可选的。A key or authorization token is optional.
  • 使用主机:传入主机地址。With a host: pass in a host address. 密钥或授权令牌是可选的。A key or authorization token is optional.
  • 使用授权令牌:传入授权令牌和关联的区域。With an authorization token: pass in an authorization token and the associated region.

让我们看看如何使用密钥和区域创建 SpeechTranslationConfigLet's take a look at how a SpeechTranslationConfig is created using a key and region. 请查看区域支持页,找到你的区域标识符。See the region support page to find your region identifier.

public class App {

    static final String SPEECH__SUBSCRIPTION__KEY = System.getenv("SPEECH__SERVICE__KEY");
    static final String SPEECH__SERVICE__REGION = System.getenv("SPEECH__SERVICE__REGION");

    public static void main(String[] args) {
        try {
            translateSpeech();
            System.exit(0);
        } catch (Exception ex) {
            System.out.println(ex);
            System.exit(1);
        }
    }

    static void translateSpeech() {
        SpeechTranslationConfig config = SpeechTranslationConfig.fromSubscription(
            SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    }
}

更改源语言Change source language

语音翻译的一项常见任务是指定输入(或源)语言。One common task of speech translation is specifying the input (or source) language. 让我们看看如何将输入语言更改为意大利语。Let's take a look at how you would change the input language to Italian. 在代码中与 SpeechTranslationConfig 实例交互,调用 setSpeechRecognitionLanguage 方法。In your code, interact with the SpeechTranslationConfig instance, calling the setSpeechRecognitionLanguage method.

static void translateSpeech() {
    SpeechTranslationConfig translationConfig = SpeechTranslationConfig.fromSubscription(
        SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    
    // Source (input) language
    translationConfig.setSpeechRecognitionLanguage("ko-KR");
}

setSpeechRecognitionLanguage 函数需要语言区域设置格式字符串。The setSpeechRecognitionLanguage function expects a language-locale format string. 可以提供受支持的区域设置/语言的列表中“区域设置”列中的任何值 。You can provide any value in the Locale column in the list of supported locales/languages.

添加翻译语言Add translation language

语音翻译的另一项常见任务是指定目标翻译语言,至少需要一种语言,但支持多种语言。Another common task of speech translation is to specify target translation languages, at least one is required but multiples are supported. 在以下代码片段中,法语和德语都作为目标翻译语言。In the following code snippet, both French and German as translation language targets.

static void translateSpeech() {
    SpeechTranslationConfig translationConfig = SpeechTranslationConfig.fromSubscription(
        SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    
    translationConfig.setSpeechRecognitionLanguage("ko-KR");

    // Translate to languages. See, https://aka.ms/speech/sttt-languages
    translationConfig.addTargetLanguage("fr");
    translationConfig.addTargetLanguage("de");
}

每次调用 addTargetLanguage 时,都会指定一种新的目标翻译语言。With every call to addTargetLanguage, a new target translation language is specified. 换言之,根据源语言识别语音后,就会在接着进行的翻译操作过程中提供每项目标翻译。In other words, when speech is recognized from the source language, each target translation is available as part of the resulting translation operation.

初始化翻译识别器Initialize a translation recognizer

创建 SpeechTranslationConfig 后,下一步是初始化 TranslationRecognizerAfter you've created a SpeechTranslationConfig, the next step is to initialize a TranslationRecognizer. 初始化 TranslationRecognizer 时,需要向其传递 translationConfigWhen you initialize a TranslationRecognizer, you'll need to pass it your translationConfig. 配置对象会提供验证你的请求时语音服务所需的凭据。The configuration object provides the credentials that the speech service requires to validate your request.

如果使用设备的默认麦克风识别语音,则 TranslationRecognizer 应如下所示:If you're recognizing speech using your device's default microphone, here's what the TranslationRecognizer should look like:

static void translateSpeech() {
    SpeechTranslationConfig translationConfig = SpeechTranslationConfig.fromSubscription(
        SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    
    String fromLanguage = "en-US";
    String[] toLanguages = { "ko", "fr", "de" };
    translationConfig.setSpeechRecognitionLanguage(fromLanguage);
    for (String language : toLanguages) {
        translationConfig.addTargetLanguage(language);
    }

    try (TranslationRecognizer recognizer = new TranslationRecognizer(translationConfig)) {
    }
}

如果要指定音频输入设备,则需要创建一个 AudioConfig 并在初始化 TranslationRecognizer 时提供 audioConfig 参数。If you want to specify the audio input device, then you'll need to create an AudioConfig and provide the audioConfig parameter when initializing your TranslationRecognizer.

首先,引用 AudioConfig 对象,如下所示:First, you'll reference the AudioConfig object as follows:

static void translateSpeech() {
    SpeechTranslationConfig translationConfig = SpeechTranslationConfig.fromSubscription(
        SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    
    String fromLanguage = "en-US";
    String[] toLanguages = { "ko", "fr", "de" };
    translationConfig.setSpeechRecognitionLanguage(fromLanguage);
    for (String language : toLanguages) {
        translationConfig.addTargetLanguage(language);
    }

    AudioConfig audioConfig = AudioConfig.fromDefaultMicrophoneInput();
    try (TranslationRecognizer recognizer = new TranslationRecognizer(translationConfig, audioConfig)) {
        
    }
}

如果要提供音频文件而不是使用麦克风,则仍需要提供 audioConfigIf you want to provide an audio file instead of using a microphone, you'll still need to provide an audioConfig. 但是,在创建 AudioConfig(而不是调用 fromDefaultMicrophoneInput)时,将调用 fromWavFileInput 并传递 filename 参数。However, when you create an AudioConfig, instead of calling fromDefaultMicrophoneInput, you'll call fromWavFileInput and pass the filename parameter.

static void translateSpeech() {
    SpeechTranslationConfig translationConfig = SpeechTranslationConfig.fromSubscription(
        SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    
    String fromLanguage = "en-US";
    String[] toLanguages = { "ko", "fr", "de" };
    translationConfig.setSpeechRecognitionLanguage(fromLanguage);
    for (String language : toLanguages) {
        translationConfig.addTargetLanguage(language);
    }

    AudioConfig audioConfig = AudioConfig.fromWavFileInput("YourAudioFile.wav");
    try (TranslationRecognizer recognizer = new TranslationRecognizer(translationConfig, audioConfig)) {
        
    }
}

翻译语音Translate speech

为了翻译语音,语音 SDK 依赖于麦克风或音频文件输入。To translate speech, the Speech SDK relies on a microphone or an audio file input. 在语音翻译之前先进行语音识别。Speech recognition occurs before speech translation. 初始化所有对象后,调用识别一次的函数并获取结果。After all objects have been initialized, call the recognize-once function and get the result.

static void translateSpeech() throws ExecutionException, InterruptedException {
    SpeechTranslationConfig translationConfig = SpeechTranslationConfig.fromSubscription(
        SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    
    String fromLanguage = "en-US";
    String[] toLanguages = { "ko", "fr", "de" };
    translationConfig.setSpeechRecognitionLanguage(fromLanguage);
    for (String language : toLanguages) {
        translationConfig.addTargetLanguage(language);
    }

    try (TranslationRecognizer recognizer = new TranslationRecognizer(translationConfig)) {
        System.out.printf("Say something in '%s' and we'll translate...", fromLanguage);

        TranslationRecognitionResult result = recognizer.recognizeOnceAsync().get();
        if (result.getReason() == ResultReason.TranslatedSpeech) {
            System.out.printf("Recognized: \"%s\"\n", result.getText());
            for (Map.Entry<String, String> pair : result.getTranslations().entrySet()) {
                System.out.printf("Translated into '%s': %s\n", pair.getKey(), pair.getValue());
            }
        }
    }
}

有关语音转文本的详细信息,请参阅语音识别基础知识For more information about speech-to-text, see the basics of speech recognition.

合成翻译Synthesize translations

成功进行语音识别和翻译后,结果会包含字典中的所有翻译。After a successful speech recognition and translation, the result contains all the translations in a dictionary. getTranslations 函数会返回一个字典,其键是目标翻译语言,其值是已翻译的文本。The getTranslations function returns a dictionary with the key as the target translation language and the value is the translated text. 可以翻译已识别的语音,然后以另一种语言进行合成(语音转语音)。Recognized speech can be translated, then synthesized in a different language (speech-to-speech).

基于事件的合成Event-based synthesis

TranslationRecognizer 对象公开了 synthesizing 事件。The TranslationRecognizer object exposes a synthesizing event. 该事件触发多次,并提供一种从翻译识别结果检索合成音频的机制。The event fires several times, and provides a mechanism to retrieve the synthesized audio from the translation recognition result. 若要翻译为多种语言,请参阅手动合成If you're translating to multiple languages, see manual synthesis. 通过分配 setVoiceName 指定合成语音,并为 synthesizing 事件提供事件处理程序,获取音频。Specify the synthesis voice by assigning a setVoiceName and provide an event handler for the synthesizing event, get the audio. 以下示例将已翻译的音频另存为 .wav 文件。The following example saves the translated audio as a .wav file.

重要

基于事件的合成仅适用于单项翻译,请勿 添加多种目标翻译语言。The event-based synthesis only works with a single translation, do not add multiple target translation languages. 此外,setVoiceName 应与目标翻译语言相同(例如,"de" 可映射到 "de-DE-Hedda")。Additionally, the setVoiceName should be the same language as the target translation language, for example; "de" could map to "de-DE-Hedda".

static void translateSpeech() throws ExecutionException, FileNotFoundException, InterruptedException, IOException {
    SpeechTranslationConfig translationConfig = SpeechTranslationConfig.fromSubscription(
        SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);

    String fromLanguage = "en-US";
    String toLanguage = "de";
    translationConfig.setSpeechRecognitionLanguage(fromLanguage);
    translationConfig.addTargetLanguage(toLanguage);

    // See: https://aka.ms/speech/sdkregion#standard-and-neural-voices
    translationConfig.setVoiceName("de-DE-Hedda");

    try (TranslationRecognizer recognizer = new TranslationRecognizer(translationConfig)) {
        recognizer.synthesizing.addEventListener((s, e) -> {
            byte[] audio = e.getResult().getAudio();
            int size = audio.length;
            System.out.println("Audio synthesized: " + size + " byte(s)" + (size == 0 ? "(COMPLETE)" : ""));

            if (size > 0) {
                try (FileOutputStream file = new FileOutputStream("translation.wav")) {
                    file.write(audio);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });

        System.out.printf("Say something in '%s' and we'll translate...", fromLanguage);

        TranslationRecognitionResult result = recognizer.recognizeOnceAsync().get();
        if (result.getReason() == ResultReason.TranslatedSpeech) {
            System.out.printf("Recognized: \"%s\"\n", result.getText());
            for (Map.Entry<String, String> pair : result.getTranslations().entrySet()) {
                String language = pair.getKey();
                String translation = pair.getValue();
                System.out.printf("Translated into '%s': %s\n", language, translation);
            }
        }
    }
}

手动合成Manual synthesis

getTranslations 函数返回一个字典,可使用该字典从翻译文本合成音频。The getTranslations function returns a dictionary that can be used to synthesize audio from the translation text. 循环访问每项翻译,并合成翻译。Iterate through each translation, and synthesize the translation. 创建 SpeechSynthesizer 实例时,SpeechConfig 对象需要将其 setSpeechSynthesisVoiceName 属性设为所需的语音。When creating a SpeechSynthesizer instance, the SpeechConfig object needs to have its setSpeechSynthesisVoiceName property set to the desired voice. 以下示例翻译为五种语言,然后将每种翻译合成为相应神经语言的音频文件。The following example translates to five languages, and each translation is then synthesized to an audio file in the corresponding neural language.

static void translateSpeech() throws ExecutionException, InterruptedException {
    SpeechTranslationConfig translationConfig = SpeechTranslationConfig.fromSubscription(
        SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
    
    String fromLanguage = "en-US";
    String[] toLanguages = { "de", "en", "zh-Hans" };
    translationConfig.setSpeechRecognitionLanguage(fromLanguage);
    for (String language : toLanguages) {
        translationConfig.addTargetLanguage(language);
    }

    try (TranslationRecognizer recognizer = new TranslationRecognizer(translationConfig)) {
        System.out.printf("Say something in '%s' and we'll translate...", fromLanguage);

        TranslationRecognitionResult result = recognizer.recognizeOnceAsync().get();
        if (result.getReason() == ResultReason.TranslatedSpeech) {
            // See: https://aka.ms/speech/sdkregion#standard-and-neural-voices
            Map<String, String> languageToVoiceMap = new HashMap<String, String>();
            languageToVoiceMap.put("de", "de-DE-KatjaNeural");
            languageToVoiceMap.put("en", "en-US-AriaNeural");
            languageToVoiceMap.put("zh-Hans", "zh-CN-XiaoxiaoNeural");

            System.out.printf("Recognized: \"%s\"\n", result.getText());
            for (Map.Entry<String, String> pair : result.getTranslations().entrySet()) {
                String language = pair.getKey();
                String translation = pair.getValue();
                System.out.printf("Translated into '%s': %s\n", language, translation);

                SpeechConfig speechConfig =
                    SpeechConfig.fromSubscription(SPEECH__SUBSCRIPTION__KEY, SPEECH__SERVICE__REGION);
                speechConfig.setSpeechSynthesisVoiceName(languageToVoiceMap.get(language));

                AudioConfig audioConfig = AudioConfig.fromWavFileOutput(language + "-translation.wav");
                try (SpeechSynthesizer synthesizer = new SpeechSynthesizer(speechConfig, audioConfig)) {
                    synthesizer.SpeakTextAsync(translation).get();
                }
            }
        }
    }
}

有关语音合成的详细信息,请参阅语音合成基础知识For more information about speech synthesis, see the basics of speech synthesis.

先决条件Prerequisites

本文假设已有一个 Azure 帐户和语音服务订阅。This article assumes that you have an Azure account and Speech service subscription. 如果你没有帐户和订阅,可免费试用语音服务If you don't have an account and subscription, try the Speech service for free.

安装语音 SDKInstall the Speech SDK

需要先安装语音 SDK,然后才能执行任何操作。Before you can do anything, you'll need to install the Speech SDK. 根据你的平台,按照“语音 SDK”一文的获取语音 SDK 部分中的说明进行操作。Depending on your platform, follow the instructions under the Get the Speech SDK section of the Speech SDK article.

导入依赖项Import dependencies

若要运行本文中的示例,请在 python 代码文件的顶部添加以下 import 语句。To run the examples in this article, include the following import statements at the top of the python code file.

import os
import azure.cognitiveservices.speech as speechsdk

敏感数据和环境变量Sensitive data and environment variables

本文中的示例源代码依赖于用于存储敏感数据的环境变量,如语音资源订阅密钥和区域。The example source code in this article depends on environment variables for storing sensitive data, such as the Speech resource subscription key and region. python 代码文件包含从主机环境变量(即 SPEECH__SUBSCRIPTION__KEYSPEECH__SERVICE__REGION)分配的两个值。The python code file contains two values that are assigned from the host machines environment variables, namely SPEECH__SUBSCRIPTION__KEY and SPEECH__SERVICE__REGION. 这两个变量都位于全局范围内,因此可以在代码文件的函数定义内访问它们。Both of these variables are at the global scope, making them accessible within function definition of the code file.

speech_key, service_region = os.environ['SPEECH__SUBSCRIPTION__KEY'], os.environ['SPEECH__SERVICE__REGION']

创建语音翻译配置Create a speech translation configuration

若要使用语音 SDK 调用语音服务,需要创建 SpeechTranslationConfigTo call the Speech service using the Speech SDK, you need to create a SpeechTranslationConfig. 此类包含有关订阅的信息,例如密钥和关联的区域、终结点、主机或授权令牌。This class includes information about your subscription, like your key and associated region, endpoint, host, or authorization token.

提示

无论是要执行语音识别、语音合成、翻译还是意向识别,都需要创建一个配置。Regardless of whether you're performing speech recognition, speech synthesis, translation, or intent recognition, you'll always create a configuration.

可以通过以下几种方法初始化 SpeechTranslationConfigThere are a few ways that you can initialize a SpeechTranslationConfig:

  • 使用订阅:传入密钥和关联的区域。With a subscription: pass in a key and the associated region.
  • 使用终结点:传入语音服务终结点。With an endpoint: pass in a Speech service endpoint. 密钥或授权令牌是可选的。A key or authorization token is optional.
  • 使用主机:传入主机地址。With a host: pass in a host address. 密钥或授权令牌是可选的。A key or authorization token is optional.
  • 使用授权令牌:传入授权令牌和关联的区域。With an authorization token: pass in an authorization token and the associated region.

让我们看看如何使用密钥和区域创建 SpeechTranslationConfigLet's take a look at how a SpeechTranslationConfig is created using a key and region. 请查看区域支持页,找到你的区域标识符。See the region support page to find your region identifier.

from_language, to_language = 'en-US', 'de'

def translate_speech_to_text():
    translation_config = speechsdk.translation.SpeechTranslationConfig(
            subscription=speech_key, region=service_region)

更改源语言Change source language

语音翻译的一项常见任务是指定输入(或源)语言。One common task of speech translation is specifying the input (or source) language. 让我们看看如何将输入语言更改为意大利语。Let's take a look at how you would change the input language to Italian. 在代码中与 SpeechTranslationConfig 实例交互,为 speech_recognition_language 属性赋值。In your code, interact with the SpeechTranslationConfig instance, assigning to the speech_recognition_language property.

def translate_speech_to_text():
    translation_config = speechsdk.translation.SpeechTranslationConfig(
            subscription=speech_key, region=service_region)

    # Source (input) language
    translation_config.speech_recognition_language = from_language

speech_recognition_language 属性需要语言区域设置格式字符串。The speech_recognition_language property expects a language-locale format string. 可以提供受支持的区域设置/语言的列表中“区域设置”列中的任何值 。You can provide any value in the Locale column in the list of supported locales/languages.

添加翻译语言Add translation language

语音翻译的另一项常见任务是指定目标翻译语言,至少需要一种语言,但支持多种语言。Another common task of speech translation is to specify target translation languages, at least one is required but multiples are supported. 在以下代码片段中,法语和德语都作为目标翻译语言。In the following code snippet, both French and German as translation language targets.

def translate_speech_to_text():
    translation_config = speechsdk.translation.SpeechTranslationConfig(
            subscription=speech_key, region=service_region)

    translation_config.speech_recognition_language = "ko-KR"

    # Translate to languages. See, https://aka.ms/speech/sttt-languages
    translation_config.add_target_language("fr")
    translation_config.add_target_language("de")

每次调用 add_target_language 时,都会指定一种新的目标翻译语言。With every call to add_target_language, a new target translation language is specified. 换言之,根据源语言识别语音后,就会在接着进行的翻译操作过程中提供每项目标翻译。In other words, when speech is recognized from the source language, each target translation is available as part of the resulting translation operation.

初始化翻译识别器Initialize a translation recognizer

创建 SpeechTranslationConfig 后,下一步是初始化 TranslationRecognizerAfter you've created a SpeechTranslationConfig, the next step is to initialize a TranslationRecognizer. 初始化 TranslationRecognizer 时,需要向其传递 translation_configWhen you initialize a TranslationRecognizer, you'll need to pass it your translation_config. 配置对象会提供验证你的请求时语音服务所需的凭据。The configuration object provides the credentials that the speech service requires to validate your request.

如果使用设备的默认麦克风识别语音,则 TranslationRecognizer 应如下所示:If you're recognizing speech using your device's default microphone, here's what the TranslationRecognizer should look like:

def translate_speech_to_text():
    translation_config = speechsdk.translation.SpeechTranslationConfig(
            subscription=speech_key, region=service_region)

    translation_config.speech_recognition_language = from_language
    translation_config.add_target_language(to_language)

    recognizer = speechsdk.translation.TranslationRecognizer(
            translation_config=translation_config)

如果要指定音频输入设备,则需要创建一个 AudioConfig 并在初始化 TranslationRecognizer 时提供 audio_config 参数。If you want to specify the audio input device, then you'll need to create an AudioConfig and provide the audio_config parameter when initializing your TranslationRecognizer.

首先,引用 AudioConfig 对象,如下所示:First, you'll reference the AudioConfig object as follows:

def translate_speech_to_text():
    translation_config = speechsdk.translation.SpeechTranslationConfig(
            subscription=speech_key, region=service_region)

    translation_config.speech_recognition_language = from_language
    for lang in to_languages:
        translation_config.add_target_language(lang)

    audio_config = speechsdk.audio.AudioConfig(use_default_microphone=True)
    recognizer = speechsdk.translation.TranslationRecognizer(
            translation_config=translation_config, audio_config=audio_config)

如果要提供音频文件而不是使用麦克风,则仍需要提供 audioConfigIf you want to provide an audio file instead of using a microphone, you'll still need to provide an audioConfig. 但是,在创建 AudioConfig 时,你将使用 filename="path-to-file.wav" 进行调用(而不是使用 use_default_microphone=True 进行调用),并提供 filename 参数。However, when you create an AudioConfig, instead of calling with use_default_microphone=True, you'll call with filename="path-to-file.wav" and provide the filename parameter.

def translate_speech_to_text():
    translation_config = speechsdk.translation.SpeechTranslationConfig(
            subscription=speech_key, region=service_region)

    translation_config.speech_recognition_language = from_language
    for lang in to_languages:
        translation_config.add_target_language(lang)

    audio_config = speechsdk.audio.AudioConfig(filename="path-to-file.wav")
    recognizer = speechsdk.translation.TranslationRecognizer(
            translation_config=translation_config, audio_config=audio_config)

翻译语音Translate speech

为了翻译语音,语音 SDK 依赖于麦克风或音频文件输入。To translate speech, the Speech SDK relies on a microphone or an audio file input. 在语音翻译之前先进行语音识别。Speech recognition occurs before speech translation. 初始化所有对象后,调用识别一次的函数并获取结果。After all objects have been initialized, call the recognize-once function and get the result.

import os
import azure.cognitiveservices.speech as speechsdk

speech_key, service_region = os.environ['SPEECH__SERVICE__KEY'], os.environ['SPEECH__SERVICE__REGION']
from_language, to_languages = 'en-US', 'de'

def translate_speech_to_text():
    translation_config = speechsdk.translation.SpeechTranslationConfig(
            subscription=speech_key, region=service_region)

    translation_config.speech_recognition_language = from_language
    translation_config.add_target_language(to_language)

    recognizer = speechsdk.translation.TranslationRecognizer(
            translation_config=translation_config)
    
    print('Say something...')
    result = recognizer.recognize_once()
    print(get_result_text(reason=result.reason, result=result))

def get_result_text(reason, result):
    reason_format = {
        speechsdk.ResultReason.TranslatedSpeech:
            f'RECOGNIZED "{from_language}": {result.text}\n' +
            f'TRANSLATED into "{to_language}"": {result.translations[to_language]}',
        speechsdk.ResultReason.RecognizedSpeech: f'Recognized: "{result.text}"',
        speechsdk.ResultReason.NoMatch: f'No speech could be recognized: {result.no_match_details}',
        speechsdk.ResultReason.Canceled: f'Speech Recognition canceled: {result.cancellation_details}'
    }
    return reason_format.get(reason, 'Unable to recognize speech')

translate_speech_to_text()

有关语音转文本的详细信息,请参阅语音识别基础知识For more information about speech-to-text, see the basics of speech recognition.

合成翻译Synthesize translations

成功进行语音识别和翻译后,结果会包含字典中的所有翻译。After a successful speech recognition and translation, the result contains all the translations in a dictionary. translations 字典键是目标翻译语言,其值是已翻译的文本。The translations dictionary key is the target translation language and the value is the translated text. 可以翻译已识别的语音,然后以另一种语言进行合成(语音转语音)。Recognized speech can be translated, then synthesized in a different language (speech-to-speech).

基于事件的合成Event-based synthesis

TranslationRecognizer 对象公开了 Synthesizing 事件。The TranslationRecognizer object exposes a Synthesizing event. 该事件触发多次,并提供一种从翻译识别结果检索合成音频的机制。The event fires several times, and provides a mechanism to retrieve the synthesized audio from the translation recognition result. 若要翻译为多种语言,请参阅手动合成If you're translating to multiple languages, see manual synthesis. 通过分配 voice_name 指定合成语音,并为 Synthesizing 事件提供事件处理程序,获取音频。Specify the synthesis voice by assigning a voice_name and provide an event handler for the Synthesizing event, get the audio. 以下示例将已翻译的音频另存为 .wav 文件。The following example saves the translated audio as a .wav file.

重要

基于事件的合成仅适用于单项翻译,请勿 添加多种目标翻译语言。The event-based synthesis only works with a single translation, do not add multiple target translation languages. 此外,voice_name 应与目标翻译语言相同(例如,"de" 可映射到 "de-DE-Hedda")。Additionally, the voice_name should be the same language as the target translation language, for example; "de" could map to "de-DE-Hedda".

import os
import azure.cognitiveservices.speech as speechsdk

speech_key, service_region = os.environ['SPEECH__SERVICE__KEY'], os.environ['SPEECH__SERVICE__REGION']
from_language, to_language = 'en-US', 'de'

def translate_speech_to_text():
    translation_config = speechsdk.translation.SpeechTranslationConfig(
            subscription=speech_key, region=service_region)

    translation_config.speech_recognition_language = from_language
    translation_config.add_target_language(to_language)

    # See: https://aka.ms/speech/sdkregion#standard-and-neural-voices
    translation_config.voice_name = "de-DE-Hedda"

    recognizer = speechsdk.translation.TranslationRecognizer(
            translation_config=translation_config)

    def synthesis_callback(evt):
        size = len(evt.result.audio)
        print(f'Audio synthesized: {size} byte(s) {"(COMPLETED)" if size == 0 else ""}')

        if size > 0:
            file = open('translation.wav', 'wb+')
            file.write(evt.result.audio)
            file.close()

    recognizer.synthesizing.connect(synthesis_callback)

    print(f'Say something in "{from_language}" and we\'ll translate into "{to_language}".')

    result = recognizer.recognize_once()
    print(get_result_text(reason=result.reason, result=result))

def get_result_text(reason, result):
    reason_format = {
        speechsdk.ResultReason.TranslatedSpeech:
            f'Recognized "{from_language}": {result.text}\n' +
            f'Translated into "{to_language}"": {result.translations[to_language]}',
        speechsdk.ResultReason.RecognizedSpeech: f'Recognized: "{result.text}"',
        speechsdk.ResultReason.NoMatch: f'No speech could be recognized: {result.no_match_details}',
        speechsdk.ResultReason.Canceled: f'Speech Recognition canceled: {result.cancellation_details}'
    }
    return reason_format.get(reason, 'Unable to recognize speech')

translate_speech_to_text()

手动合成Manual synthesis

translations 字典可用于从翻译文本合成音频。The translations dictionary can be used to synthesize audio from the translation text. 循环访问每项翻译,并合成翻译。Iterate through each translation, and synthesize the translation. 创建 SpeechSynthesizer 实例时,SpeechConfig 对象需要将其 speech_synthesis_voice_name 属性设为所需的语音。When creating a SpeechSynthesizer instance, the SpeechConfig object needs to have its speech_synthesis_voice_name property set to the desired voice. 以下示例翻译为五种语言,然后将每种翻译合成为相应神经语言的音频文件。The following example translates to five languages, and each translation is then synthesized to an audio file in the corresponding neural language.

import os
import azure.cognitiveservices.speech as speechsdk

speech_key, service_region = os.environ['SPEECH__SERVICE__KEY'], os.environ['SPEECH__SERVICE__REGION']
from_language, to_languages = 'en-US', [ 'de', 'en', 'zh-Hans' ]

def translate_speech_to_text():
    translation_config = speechsdk.translation.SpeechTranslationConfig(
            subscription=speech_key, region=service_region)

    translation_config.speech_recognition_language = from_language
    for lang in to_languages:
        translation_config.add_target_language(lang)

    recognizer = speechsdk.translation.TranslationRecognizer(
            translation_config=translation_config)
    
    print('Say something...')
    result = recognizer.recognize_once()
    synthesize_translations(result=result)

def synthesize_translations(result):
    language_to_voice_map = {
        "de": "de-DE-KatjaNeural",
        "en": "en-US-AriaNeural",
        "zh-Hans": "zh-CN-XiaoxiaoNeural"
    }
    print(f'Recognized: "{result.text}"')

    for language in result.translations:
        translation = result.translations[language]
        print(f'Translated into "{language}": {translation}')

        speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
        speech_config.speech_synthesis_voice_name = language_to_voice_map.get(language)
        
        audio_config = speechsdk.audio.AudioOutputConfig(filename=f'{language}-translation.wav')
        speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)
        speech_synthesizer.speak_text_async(translation).get()

translate_speech_to_text()

有关语音合成的详细信息,请参阅语音合成基础知识For more information about speech synthesis, see the basics of speech synthesis.

其他语言和平台支持Additional language and platform support

如果已单击此选项卡,则可能看不到你偏好的编程语言的基础知识文章。If you've clicked this tab, you probably didn't see a basics article in your favorite programming language. 别担心,我们在 GitHub 上提供了其他代码示例。Don't worry, we have additional code samples available on GitHub. 使用表格查找适用于编程语言和平台/OS 组合的相应示例。Use the table to find the right sample for your programming language and platform/OS combination.

语言Language 代码示例Code samples
C#C# .NET Framework.NET CoreUWPUnityXamarin.NET Framework, .NET Core, UWP, Unity, Xamarin
C++C++ 快速入门示例Quickstarts, Samples
JavaJava AndroidJREAndroid, JRE
JavascriptJavaScript 浏览器Browser
Node.jsNode.js Windows、Linux 和 macOSWindows, Linux, macOS
Objective-CObjective-C iOSmacOSiOS, macOS
PythonPython Windows、Linux 和 macOSWindows, Linux, macOS
SwiftSwift iOSmacOSiOS, macOS

后续步骤Next steps