快速入門:使用適用於 .NET Core 的語音 SDK 來辨識語音Quickstart: Recognize speech with the Speech SDK for .NET Core

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

如有需要,請選擇不同的程式設計語言和/或環境:If desired, choose a different programming language and/or environment:

在本文中,您會透過使用認知服務語音 SDK,在 Windows 或 macOS 上的 .NET Core 建立 C# 主控台應用程式。In this article, you create a C# console application for .NET Core on Windows or macOS by using the Cognitive Services Speech SDK. 您將來自電腦麥克風的語音即時轉譯為文字。You transcribe speech to text in real time from your PC's microphone. 應用程式是利用語音 SDK NuGet 套件與 Microsoft Visual Studio 2017 (任何版本) 所建置的。The application is built with the Speech SDK NuGet package and Microsoft Visual Studio 2017 (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 RecognizeSpeechAsync()
            {
                // 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 recognizer.
                using (var recognizer = new SpeechRecognizer(config))
                {
                    Console.WriteLine("Say something...");
    
                    // Starts speech recognition, and returns after a single utterance is recognized. The end of a
                    // single utterance is determined by listening for silence at the end or until a maximum of 15
                    // seconds of audio is processed.  The task returns the recognition text as result. 
                    // Note: Since RecognizeOnceAsync() returns only a single utterance, it is suitable only for single
                    // shot recognition like command or query. 
                    // For long-running multi-utterance recognition, use StartContinuousRecognitionAsync() instead.
                    var result = await recognizer.RecognizeOnceAsync();
    
                    // Checks result.
                    if (result.Reason == ResultReason.RecognizedSpeech)
                    {
                        Console.WriteLine($"We recognized: {result.Text}");
                    }
                    else if (result.Reason == ResultReason.NoMatch)
                    {
                        Console.WriteLine($"NOMATCH: Speech could not be recognized.");
                    }
                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = CancellationDetails.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()
            {
                RecognizeSpeechAsync().Wait();
                Console.WriteLine("Please press a key to continue.");
                Console.ReadLine();
            }
        }
    }
    
  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 Services and transcribed to text, which appears in the same window.

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

後續步驟Next steps

在 GitHub 上可取得其他範例,例如如何讀取音訊檔案中的語音。Additional samples, such as how to read speech from an audio file, are available on GitHub.

另請參閱See also