快速入門:使用適用於 .NET Core 的語音 SDK 來合成語音Quickstart: Synthesize speech with the Speech SDK for .NET Core

另備有語音辨識語音翻譯的快速入門。Quickstarts are also available for speech-recognition and speech-translation.

在本文中,您會透過使用認知服務語音 SDK,在 Windows 上的 .NET Core 建立 C# 主控台應用程式。In this article, you create a C# console application for .NET Core on Windows by using the Cognitive Services Speech SDK. 您會從文字合成語音並即時傳至電腦喇叭。You synthesize speech from text in real time to your PC's speaker. 應用程式是利用語音 SDK NuGet 套件與 Microsoft Visual Studio 2017 或更新版本 (任何版本) 所建置的。The application is built with the Speech SDK NuGet package and Microsoft Visual Studio 2017 or later (any edition).

注意

.NET Core 是實作.NET Standard 規格的開放原始碼、跨平台 .NET 平台。.NET Core is an open-source, cross-platform .NET platform that implements the .NET Standard specification.

您需要語音服務訂用帳戶金鑰,才能完成本快速入門。You need a Speech Services subscription key to complete this Quickstart. 您可以免費取得一個金鑰。You can get one for free. 如需詳細資訊,請參閱免費試用語音服務See Try the Speech Services for free for details.

必要條件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;
    
    namespace helloworld
    {
        class Program
        {
            public static async Task SynthesisToSpeakerAsync()
            {
                // Creates an instance of a speech config with specified subscription key and service region.
                // Replace with your own subscription key and service region (e.g., "westus").
                var config = SpeechConfig.FromSubscription("YourSubscriptionKey", "YourServiceRegion");
    
                // Creates a speech synthesizer using the default speaker as audio output.
                using (var synthesizer = new SpeechSynthesizer(config))
                {
                    // Receive a text from console input and synthesize it to speaker.
                    Console.WriteLine("Type some text that you want to speak...");
                    Console.Write("> ");
                    string text = Console.ReadLine();
    
                    using (var result = await synthesizer.SpeakTextAsync(text))
                    {
                        if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                        {
                            Console.WriteLine($"Speech synthesized to speaker for text [{text}]");
                        }
                        else if (result.Reason == ResultReason.Canceled)
                        {
                            var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                            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 update the subscription info?");
                            }
                        }
                    }
                }
            }
    
            static void Main()
            {
                SynthesisToSpeakerAsync().Wait();
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
    }
    
  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 type some text. 請輸入幾個字或句子。Type a few words or a sentence. 您輸入的文字會傳送至語音服務並合成為語音,然後以喇叭播放。The text that you typed is transmitted to the Speech Services and synthesized to speech, which plays on your speaker.

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

後續步驟Next steps

在 GitHub 上可取得其他範例,例如如何將語音合成至音訊檔案。Additional samples, such as how to synthesize speech to an audio file, are available on GitHub.

另請參閱See also