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

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

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

您可以使用本指南,透過 .NET Framework for Windows 和語音 SDK 建立語音轉換文字的主控台應用程式。Use this guide to create a speech-to-text console application using the .NET framework for Windows and the Speech SDK. 完成之後,您可以使用電腦的麥克風將語音即時轉譯為文字。When finished, you can use your computer's microphone to transcribe speech to text in real time.

如需快速示範 (不自行建置 Visual Studio 專案,如下所示):For a quick demonstration (without building the Visual Studio project yourself as shown below):

從 GitHub 取得最新的認知服務語音 SDK 範例Get the latest Cognitive Services Speech SDK Samples from GitHub.

必要條件Prerequisites

若要完成此專案,您需要:To complete this project, you'll need:

建立 Visual Studio 專案Create a Visual Studio project

  1. 開啟 Visual Studio 2019。Open Visual Studio 2019.

  2. 在 [開始] 視窗中,選取 [建立新專案] 。In the Start window, select Create a new project.

  3. 選取 [主控台應用程式 (.NET Framework)] ,然後選取 [下一步] 。Select Console App (.NET Framework), and then select Next.

  4. 在 [專案名稱] 中,輸入 helloworld,然後選取 [建立] 。In Project name, enter helloworld, and then select Create.

  5. 從 Visual Studio 的功能表列,選取 [工具] > [取得工具和功能] ,並檢查 .NET 桌面開發工作負載是否可用。From the menu bar in Visual Studio, select Tools > Get Tools and Features, and check whether the .NET desktop development workload is available. 如果尚未安裝工作負載,請勾選核取方塊,然後選取 [修改] 以開始安裝。If the workload hasn't been installed, mark the checkbox, then select Modify to start the installation. 下載及安裝可能需要幾分鐘的時間。It may take a few minutes to download and install.

    如果 .NET 桌面開發 旁邊的核取方塊已選取,您現在可以關閉對話方塊。If the checkbox next to .NET desktop development is selected, you can close the dialog box now.

    啟用 .NET 桌面開發

下一個步驟是安裝 語音 SDK NuGet 套件,所以您可在程式碼中參考它。The next step is to install the Speech SDK NuGet package, so you can reference it in the code.

  1. 在 [方案總管] 中,以滑鼠右鍵按一下 helloworld,然後選取 [管理 NuGet 套件] 以顯示 NuGet 套件管理員。In the Solution Explorer, right-click helloworld, and then select Manage NuGet Packages to show the NuGet Package Manager.

    NuGet 套件管理員

  2. 在右上角找到 [套件來源] 下拉式方塊,並確定已選取 [nuget.org] 。In the upper-right corner, find the Package Source drop-down box, and make sure that nuget.org is selected.

  3. 選取左上角的 [瀏覽] 。In the upper-left corner, select Browse.

  4. 在搜尋方塊中,輸入 Microsoft.CognitiveServices.Speech 套件並按 Enter 鍵。In the search box, type Microsoft.CognitiveServices.Speech package and press Enter.

  5. 選取 Microsoft.CognitiveServices.Speech,然後選取 [安裝] 以安裝最新的穩定版本。Select Microsoft.CognitiveServices.Speech, and then select Install to install the latest stable version.

    安裝 Microsoft.CognitiveServices.Speech NuGet 套件

  6. 接受所有合約和授權,即可開始安裝。Accept all agreements and licenses to start the installation.

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

現在,若要建置及執行主控台應用程式,請建立符合電腦架構的平台組態。Now, to build and run the console application, create a platform configuration matching your computer's architecture.

  1. 從功能表列選取 [建置] > [組態管理員] 。From the menu bar, select Build > Configuration Manager. [組態管理員] 對話方塊隨即出現。The Configuration Manager dialog box appears.

    組態管理員對話方塊

  2. 在 [使用中的方案平台] 下拉式方塊中,選取 [新增] 。In the Active solution platform drop-down box, select New. [新增方案平台] 對話方塊隨即出現。The New Solution Platform dialog box appears.

  3. 在 [輸入或選取新平台] 下拉式方塊中:In the Type or select the new platform drop-down box:

    • 如果您執行 64 位元的 Windows,請選取 x64If you're running 64-bit Windows, select x64.
    • 如果您執行 32 位元的 Windows,請選取 x86If you're running 32-bit Windows, select x86.
  4. 選取 [確定] ,然後選取 [關閉] 。Select OK and then Close.

新增範例程式碼Add sample code

  1. 開啟 Program.cs,並將自動產生的程式碼取代下列範例:Open Program.cs and replace the automatically generated code with this sample:

    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 並將其取代為您的語音服務訂用帳戶金鑰。Locate and replace the string YourSubscriptionKey with your Speech Services subscription key.

  3. 找出字串 YourServiceRegion 並將其取代為與您的訂用帳戶相關聯的區域Locate and replace the string YourServiceRegion with the region associated with your subscription. 例如,如果您使用的是免費試用版,區域將是 westusFor example, if you're using the free trial, the region is westus.

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

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

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

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

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

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

  3. 此時會出現一個主控台視窗,提示您開始說話。A console window will appear, prompting you to speak. 現在,請說一些英文。Now, say something in English. 您的語音會傳送到語音服務,並即時轉譯為文字。Your speech is transmitted to the Speech Services and transcribed to text in real time. 結果會印出到主控台。The result is printed to the console.

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

後續步驟Next steps

另請參閱See also