快速入門:使用適用於 .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 2017。Start Visual Studio 2017.

  2. 從 Visual Studio 的功能表列,選取 [工具] > [取得工具] ,並確定 .NET 桌面開發工作負載可供使用。From the menu bar in Visual Studio, select Tools > Get Tools and make sure that the .NET desktop development workload is available. 如果尚未安裝工作負載,請勾選核取方塊,然後按一下 [修改] 以開始安裝。If the workload hasn't been installed, mark the checkbox, then click 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 桌面開發

  3. 接下來,我們來建立專案。Next, let's create a project. 從功能表列,選取 [檔案] > [新增] > [專案] 。From the menu bar select File > New > Project. 當對話方塊出現時,從左側面板展開 [已安裝] > [Visual C#] > [Windows 桌面] 區段,然後選取 [主控台應用程式 (.NET Framework)] 。When the dialog box appears, from the left panel expand these sections Installed > Visual C# > Windows Desktop and select Console App (.NET Framework). 將此專案命名為 helloworld 。Name this project helloworld.

    建立 Visual C# 主控台應用程式 (.NET Framework)Create Visual C# Console App (.NET Framework)

  4. 現在,專案設定好之後,我們必須安裝語音 SDK NuGet 套件,並在我們的程式碼中參考此套件。Now that the project is set up, we need to install the Speech SDK NuGet package and reference it in our code. 找出 [方案總管],並以滑鼠右鍵按一下 helloworld。Locate the Solution Explorer and right-click on helloworld. 在功能表上,選取 [管理 NuGet 套件...] 。From the menu, select Manage NuGet Packages....

    以滑鼠右鍵按一下解決方案的管理 NuGet 封裝Right-click Manage NuGet Packages for Solution

  5. 在 NuGet 套件管理員的右上角,找到 [套件來源] 下拉式清單,並確定 [nuget.org] 已選取。In the upper-right corner of the NuGet Package Manager, locate the Package Source dropdown and make sure that nuget.org is selected. 然後,選取 [瀏覽] 並搜尋 Microsoft.CognitiveServices.Speech 套件,然後安裝最新的穩定版本。Then, select Browse and search for the Microsoft.CognitiveServices.Speech package and install the latest stable version.

    安裝 Microsoft.CognitiveServices.Speech NuGet 套件Install Microsoft.CognitiveServices.Speech NuGet Package

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

    接受授權Accept the license

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

  7. 下一個步驟是根據您用來建置並執行主控台應用程式的電腦架構,建立與之相符的平台組態。The next step is to create a platform configuration that matches the architecture of the computer you're using to build and run the console application. 從功能表列選取 [建置] > [組態管理員...] 。From the menu bar, select Build > Configuration Manager....

    啟動組態管理員Launch the configuration manager

  8. 在 [組態管理員] 對話方塊方塊中,找到 [使用中的方案平台] 下拉式清單,然後選取 [新增] 。In the Configuration Manager dialog box, locate the Active solution platform drop-down list, and select New.

    在 [組態管理員] 視窗下方新增平台Add a new platform under the configuration manager window

  9. 如果您執行 64 位元的 Windows,出現 [輸入或選取新平台] 的提示時,請選取 x64If you are running 64-bit Windows, when prompted with Type or select the new platform, x64. 如果您執行 32 位元的 Windows,請選取 x86If you are running 32-bit Windows, select x86. 完成時,請按一下 [確定] 。When you're finished, click OK.

    在 64 位元 Windows 上新增名為「x64」的平台On 64-bit Windows, add a new platform named "x64"

新增範例程式碼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