快速入門:使用適用於 .NET Core 的語音 SDK 來翻譯語音Quickstart: Translate speech with the Speech SDK for .NET Core

另備有語音轉換文字文字轉換語音的快速入門。Quickstarts are also available for speech-to-text and text-to-speech.

在此快速入門中,您將會建立簡單的 .NET Core 應用程式以從電腦的麥克風即時擷取使用者語音,翻譯該語音,然後將翻譯的文字轉譯到命令列。In this quickstart, you'll create a simple .NET Core application that captures user speech from your computer's microphone, translates the speech, and transcribes the translated text to the command line in real time. 此應用程式是設計來在 64 位元的 Windows 上執行,而且是使用語音 SDK NuGet 套件 (英文) 和 Microsoft Visual Studio 2017 或更新版本來建置。This application is designed to run on 64-bit Windows, and is built with the Speech SDK NuGet package and Microsoft Visual Studio 2017 or later.

如需可供進行語音翻譯的完整語言清單,請參閱語言支援For a complete list of languages available for speech translation, see language support.

必要條件Prerequisites

本快速入門需要:This quickstart requires:

建立 Visual Studio 專案Create a Visual Studio project

  1. 啟動 Visual Studio 2019。Start Visual Studio 2019.

  2. 請確定 .NET 跨平台開發工作負載可用。Make sure the .NET cross-platform development workload is available. 從 Visual Studio 功能表列選擇 [工具] > [取得工具和功能] ,以開啟 Visual Studio 安裝程式。Choose Tools > Get Tools and Features from the Visual Studio menu bar to open the Visual Studio installer. 如果已啟用此工作負載,請關閉對話方塊。If this workload is already enabled, close the dialog box.

    Visual Studio 安裝程式的螢幕擷取畫面,其中 [工作負載] 索引標籤已醒目提示

    否則,選取 [.NET Core 跨平台開發] 旁邊的方塊,然後選取對話方塊右下角的 [修改] 。Otherwise, select the box next to .NET Core cross-platform development, and select Modify at the lower right corner of the dialog box. 安裝新功能需要一些時間。Installation of the new feature will take a moment.

  3. 建立新的 Visual C# .NET Core 主控台應用程式。Create a new Visual C# .NET Core Console App. 在 [新增專案] 對話方塊中,從左窗格展開 [已安裝] > [Visual C#] > [.NET Core] 。In the New Project dialog box, from the left pane, expand Installed > Visual C# > .NET Core. 然後選取 [主控台應用程式 (.NET Core)] 。Then select Console App (.NET Core). 針對專案名稱,請輸入 helloworldFor the project name, enter helloworld.

    [新增專案] 對話方塊的螢幕擷取畫面Screenshot of New Project dialog box

  4. 安裝並參考 Speech SDK NuGet 封裝Install and reference the Speech SDK NuGet package. 在 [方案總管] 中,以滑鼠右鍵按一下解決方案,然後選取 [管理解決方案的 NuGet 套件] 。In Solution Explorer, right-click the solution and select Manage NuGet Packages for Solution.

    方案總管的螢幕擷取畫面,其中 [管理解決方案的 NuGet 套件] 選項已醒目提示Screenshot of Solution Explorer, with Manage NuGet Packages for Solution highlighted

  5. 在右上角的 [套件來源] 欄位中,選取 [nuget.org] 。搜尋 Microsoft.CognitiveServices.Speech 套件,然後將它安裝到 helloworld 專案。In the upper-right corner, in the Package Source field, select nuget.org. Search for the Microsoft.CognitiveServices.Speech package, and install it into the helloworld project.

    管理解決方案套件對話方塊的螢幕擷取畫面Screenshot of Manage Packages for Solution dialog box

  6. 接受顯示的授權,才會開始安裝 NuGet 套件。Accept the displayed license to begin installation of the NuGet package.

    接受授權對話方塊的螢幕擷取畫面Screenshot of License Acceptance dialog box

安裝套件之後,[套件管理員] 主控台上會出現確認訊息。After the package is installed, a confirmation appears in the Package Manager console.

新增範例程式碼Add sample code

  1. 開啟 Program.cs 並將其中的所有程式碼取代為下列程式碼。Open Program.cs, and replace all the code in it with the following.

    using System;
    using System.Threading.Tasks;
    using Microsoft.CognitiveServices.Speech;
    using Microsoft.CognitiveServices.Speech.Translation;
    
    namespace helloworld
    {
        class Program
        {
            public static async Task TranslationContinuousRecognitionAsync()
            {
                // Creates an instance of a speech translation config with specified subscription key and service region.
                // Replace with your own subscription key and service region (e.g., "westus").
                var config = SpeechTranslationConfig.FromSubscription("YourSubscriptionKey", "YourServiceRegion");
    
                // Sets source and target languages.
                string fromLanguage = "en-US";
                config.SpeechRecognitionLanguage = fromLanguage;
                config.AddTargetLanguage("de");
    
                // Sets voice name of synthesis output.
                const string GermanVoice = "de-DE-Hedda";
                config.VoiceName = GermanVoice;
                // Creates a translation recognizer using microphone as audio input.
                using (var recognizer = new TranslationRecognizer(config))
                {
                    // Subscribes to events.
                    recognizer.Recognizing += (s, e) =>
                    {
                        Console.WriteLine($"RECOGNIZING in '{fromLanguage}': Text={e.Result.Text}");
                        foreach (var element in e.Result.Translations)
                        {
                            Console.WriteLine($"    TRANSLATING into '{element.Key}': {element.Value}");
                        }
                    };
    
                    recognizer.Recognized += (s, e) =>
                    {
                        if (e.Result.Reason == ResultReason.TranslatedSpeech)
                        {
                            Console.WriteLine($"\nFinal result: Reason: {e.Result.Reason.ToString()}, recognized text in {fromLanguage}: {e.Result.Text}.");
                            foreach (var element in e.Result.Translations)
                            {
                                Console.WriteLine($"    TRANSLATING into '{element.Key}': {element.Value}");
                            }
                        }
                    };
    
                    recognizer.Synthesizing += (s, e) =>
                    {
                        var audio = e.Result.GetAudio();
                        Console.WriteLine(audio.Length != 0
                            ? $"AudioSize: {audio.Length}"
                            : $"AudioSize: {audio.Length} (end of synthesis data)");
                    };
    
                    recognizer.Canceled += (s, e) =>
                    {
                        Console.WriteLine($"\nRecognition canceled. Reason: {e.Reason}; ErrorDetails: {e.ErrorDetails}");
                    };
    
                    recognizer.SessionStarted += (s, e) =>
                    {
                        Console.WriteLine("\nSession started event.");
                    };
    
                    recognizer.SessionStopped += (s, e) =>
                    {
                        Console.WriteLine("\nSession stopped event.");
                    };
    
                    // Starts continuous recognition. Uses StopContinuousRecognitionAsync() to stop recognition.
                    Console.WriteLine("Say something...");
                    await recognizer.StartContinuousRecognitionAsync().ConfigureAwait(false);
    
                    do
                    {
                        Console.WriteLine("Press Enter to stop");
                    } while (Console.ReadKey().Key != ConsoleKey.Enter);
    
                    // Stops continuous recognition.
                    await recognizer.StopContinuousRecognitionAsync().ConfigureAwait(false);
                }
            }
    
            static void Main(string[] args)
            {
                TranslationContinuousRecognitionAsync().Wait();
            }
        }
    }
    
  2. 在相同檔案中,以您的訂用帳戶金鑰取代 YourSubscriptionKey 字串。In the same file, replace the string YourSubscriptionKey with your subscription key.

  3. 同時以與您的訂用帳戶 (例如,免費試用訂用帳戶的 westus) 相關聯的區域取代 YourServiceRegion 字串。Also replace the string YourServiceRegion with the region associated with your subscription (for example, westus for the free trial subscription).

  4. 儲存專案的變更。Save changes to the project.

建置並執行應用程式Build and run the app

  1. 建置應用程式。Build the application. 從功能表列中,選擇 [建置] > [建置解決方案] 。From the menu bar, choose Build > Build Solution. 這應該會編譯程式碼,而且不會出現任何錯誤。The code should compile without errors.

    Visual Studio 應用程式的螢幕擷取畫面,其中 [建置解決方案] 選項已醒目提示Screenshot of Visual Studio application, with Build Solution option highlighted

  2. 啟動應用程式。Start the application. 從功能表列中,選擇 [偵錯] > [開始偵錯] ,或按 F5From the menu bar, choose Debug > Start Debugging, or press F5.

    Visual Studio 應用程式的螢幕擷取畫面,其中 [開始偵錯] 選項已醒目提示Screenshot of Visual Studio application, with Start Debugging option highlighted

  3. 一個主控台視窗隨即顯示,提示您說話。A console window appears, prompting you to say something. 請說英文片語或句子。Speak an English phrase or sentence. 您的語音會傳送到語音服務,並翻譯並轉譯為文字;該文字會出現在相同的視窗中。Your speech is transmitted to the Speech service, translated, and transcribed to text, which appears in the same window.

    成功翻譯後主控台輸出的螢幕擷取畫面Screenshot of console output after successful translation

後續步驟Next steps

在 GitHub 上可取得其他範例,例如如何讀取音訊檔案中的語音,以及將翻譯的文字輸出為合成語音。Additional samples, such as how to read speech from an audio file, and output translated text as synthesized speech, are available on GitHub.

另請參閱See also