教學課程:使用適用於 C# 的語音 SDK 從語音辨識意圖Tutorial: Recognize intents from speech using the Speech SDK for C#

認知服務語音 SDK 會與 Language Understanding Intelligent Service (LUIS) 整合以提供意圖辨識。The Cognitive Services Speech SDK integrates with the Language Understanding service (LUIS) to provide intent recognition. 意圖是使用者想要做的事情:訂機票、查看天氣或打電話。An intent is something the user wants to do: book a flight, check the weather, or make a call. 使用者可以使用任何他們覺得自然的字詞。The user can use whatever terms feel natural. 使用機器學習服務,LUIS 會將使用者要求對應至您已定義的意圖。Using machine learning, LUIS maps user requests to the intents you have defined.

注意

LUIS 應用程式 (application) 會定義您想要辨識的的意圖和實體。A LUIS application defines the intents and entities you want to recognize. 其有別於使用語音服務的 C# 應用程式 (application)。It's separate from the C# application that uses the Speech service. 在本文中,「應用程式 (app)」意指 LUIS 應用程式 (app),「應用程式 (application)」則意指 C# 程式碼。In this article, "app" means the LUIS app, while "application" means the C# code.

在本教學課程中,您會使用語音 SDK 來開發 C# 主控台應用程式 (application),其會透過裝置的麥克風從使用者的語句推導出意圖。In this tutorial, you use the Speech SDK to develop a C# console application that derives intents from user utterances through your device's microphone. 您將學習如何:You'll learn how to:

  • 建立 Visual Studio 專案,並讓其參考語音 SDK NuGet 套件Create a Visual Studio project referencing the Speech SDK NuGet package
  • 建立語音設定並取得意圖辨識器Create a speech config and get an intent recognizer
  • 取得 LUIS 應用程式 (app) 的模型,並新增所需意圖Get the model for your LUIS app and add the intents you need
  • 指定語音辨識的語言Specify the language for speech recognition
  • 從檔案辨識語音Recognize speech from a file
  • 使用非同步的事件驅動連續辨識Use asynchronous, event-driven continuous recognition

必要條件Prerequisites

開始進行本教學課程之前,請務必具備下列項目。Be sure you have the following before you begin this tutorial.

  • LUIS 帳戶。A LUIS account. 您可以透過 LUIS 入口網站免費取得。You can get one for free through the LUIS portal.
  • Visual Studio 2017 (任何版本)。Visual Studio 2017 (any edition).

LUIS 和語音LUIS and speech

LUIS 會與語音服務整合以從語音辨識意圖。LUIS integrates with the Speech Services to recognize intents from speech. 您不需要語音服務訂用帳戶,只要有 LUIS 即可。You don't need a Speech Services subscription, just LUIS.

LUIS 會使用兩種金鑰:LUIS uses two kinds of keys:

金鑰類型Key type 目的Purpose
編寫authoring 可讓您以程式設計方式建立和修改 LUIS 應用程式 (app)lets you create and modify LUIS apps programmatically
endpointendpoint 可授權特定 LUIS 應用程式 (app) 的存取權authorizes access to a particular LUIS app

端點金鑰是本教學課程需要的 LUIS 金鑰。The endpoint key is the LUIS key needed for this tutorial. 本教學課程使用「家庭自動化」LUIS 應用程式 (app) 範例,遵循使用預先建置的家庭自動化應用程式 (app) 即可建立。This tutorial uses the example Home Automation LUIS app, which you can create by following Use prebuilt Home automation app. 如果您已建立自有 LUIS 應用程式 (app),則可以改用此應用程式 (app)。If you have created a LUIS app of your own, you can use it instead.

當您建立 LUIS 應用程式 (app) 時,系統會自動產生入門金鑰,讓您可以使用文字查詢來測試應用程式 (app)。When you create a LUIS app, a starter key is automatically generated so you can test the app using text queries. 此金鑰不會啟用語音服務整合,且無法用於本教學課程。This key does not enable the Speech Services integration and won't work with this tutorial. 您必須在 Azure 儀表板中建立 LUIS 資源,並將它指派給 LUIS 應用程式 (app)。You must create a LUIS resource in the Azure dashboard and assign it to the LUIS app. 在本教學課程中,您可以使用免費訂用帳戶層。You can use the free subscription tier for this tutorial.

在 Azure 儀表板中建立 LUIS 資源之後,登入 LUIS 入口網站,在 [我的應用程式] 頁面選擇應用程式 (application),然後切換至應用程式 (app) 的 [管理] 頁面。After creating the LUIS resource in the Azure dashboard, log into the LUIS portal, choose your application on the My Apps page, then switch to the app's Manage page. 最後,按一下提要欄位中的 [金鑰和端點] 。Finally, click Keys and Endpoints in the sidebar.

LUIS 入口網站的金鑰和端點設定

在 [金鑰和端點設定] 頁面上:On the Keys and Endpoint settings page:

  1. 向下捲動至 [資源與金鑰] 區段,然後按一下 [指派資源] 。Scroll down to the Resources and Keys section and click Assign resource.

  2. 在 [對應用程式指派金鑰] 對話方塊中,選擇下列項目:In the Assign a key to your app dialog, choose the following:

    • 選擇 Microsoft 作為租用戶。Choose Microsoft as the Tenant.
    • 在 [訂用帳戶名稱] 下,選擇包含所要使用 LUIS 資源的 Azure 訂用帳戶。Under Subscription Name, choose the Azure subscription that contains the LUIS resource you want to use.
    • 在 [金鑰] 下,選擇要與應用程式 (app) 搭配使用的 LUIS 資源。Under Key, choose the LUIS resource that you want to use with the app.

稍等一會兒,新的訂用帳戶就會出現在頁面底部的資料表中。In a moment, the new subscription appears in the table at the bottom of the page. 按一下金鑰旁邊的圖示,以將它複製到剪貼簿。Click the icon next to a key to copy it to the clipboard. (您可以使用任一金鑰。)(You may use either key.)

LUIS 應用程式 (app) 訂用帳戶金鑰

在 Visual Studio 中建立語音專案Create a speech project in Visual Studio

  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 the code

開啟 Visual Studio 專案中的 Program.cs 檔案,並將檔案開頭 using 陳述式的區塊更換為下列宣告。Open the file Program.cs in the Visual Studio project and replace the block of using statements at the beginning of the file with the following declarations.

using System;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using Microsoft.CognitiveServices.Speech.Intent;

在所提供的 Main() 方法內,新增下列程式碼。Inside the provided Main() method, add the following code.

RecognizeIntentAsync().Wait();
Console.WriteLine("Please press Enter to continue.");
Console.ReadLine();

建立空白的非同步方法 RecognizeIntentAsync(),如下所示。Create an empty asynchronous method RecognizeIntentAsync(), as shown here.

static async Task RecognizeIntentAsync()
{
}

在這個新方法的主體中,新增下列程式碼。In the body of this new method, add this code.

// Creates an instance of a speech config with specified subscription key
// and service region. Note that in contrast to other services supported by
// the Cognitive Services Speech SDK, the Language Understanding service
// requires a specific subscription key from https://www.luis.ai/.
// The Language Understanding service calls the required key 'endpoint key'.
// Once you've obtained it, replace with below with your own Language Understanding subscription key
// and service region (e.g., "westus").
// The default language is "en-us".
var config = SpeechConfig.FromSubscription("YourLanguageUnderstandingSubscriptionKey", "YourLanguageUnderstandingServiceRegion");

// Creates an intent recognizer using microphone as audio input.
using (var recognizer = new IntentRecognizer(config))
{
    // Creates a Language Understanding model using the app id, and adds specific intents from your model
    var model = LanguageUnderstandingModel.FromAppId("YourLanguageUnderstandingAppId");
    recognizer.AddIntent(model, "YourLanguageUnderstandingIntentName1", "id1");
    recognizer.AddIntent(model, "YourLanguageUnderstandingIntentName2", "id2");
    recognizer.AddIntent(model, "YourLanguageUnderstandingIntentName3", "any-IntentId-here");

    // Starts recognizing.
    Console.WriteLine("Say something...");

    // Starts intent 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().ConfigureAwait(false);

    // Checks result.
    if (result.Reason == ResultReason.RecognizedIntent)
    {
        Console.WriteLine($"RECOGNIZED: Text={result.Text}");
        Console.WriteLine($"    Intent Id: {result.IntentId}.");
        Console.WriteLine($"    Language Understanding JSON: {result.Properties.GetProperty(PropertyId.LanguageUnderstandingServiceResponse_JsonResult)}.");
    }
    else if (result.Reason == ResultReason.RecognizedSpeech)
    {
        Console.WriteLine($"RECOGNIZED: Text={result.Text}");
        Console.WriteLine($"    Intent not recognized.");
    }
    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?");
        }
    }
}

將這個方法中的預留位置更換為 LUIS 訂用帳戶金鑰、區域和應用程式 (app) 識別碼,如下所示。Replace the placeholders in this method with your LUIS subscription key, region, and app ID as follows.

PlaceholderPlaceholder 更換為Replace with
YourLanguageUnderstandingSubscriptionKey LUIS 端點金鑰。Your LUIS endpoint key. 如先前所述,這必須是取自 Azure 儀表板的金鑰,而非「入門金鑰」。As previously noted, this must be a key obtained from your Azure dashboard, not a "starter key." 此金鑰可在 LUIS 入口網站中的應用程式 (app) [金鑰和端點] 頁面 (在 [管理] 底下) 中找到。You can find it on your app's Keys and Endpoints page (under Manage) in the LUIS portal.
YourLanguageUnderstandingServiceRegion LUIS 訂用帳戶所在區域的簡短識別碼,例如美國西部是 westusThe short identifier for the region your LUIS subscription is in, such as westus for West US. 請參閱區域See Regions.
YourLanguageUnderstandingAppId LUIS 應用程式識別碼。The LUIS app ID. 您可以在 LUIS 入口網站的應用程式 (app) [設定] 頁面上找到此值。You can find it on your app's Settings page of the LUIS portal.

進行這些變更後,您就可以建置 (Control-Shift-B) 並執行 (F5) 教學課程的應用程式 (application)。With these changes made, you can build (Control-Shift-B) and run (F5) the tutorial application. 出現提示時,請試著對電腦的麥克風說「關燈」。When prompted, try saying "Turn off the lights" into your PC's microphone. 結果會顯示在主控台視窗中。The result is displayed in the console window.

下列幾節會討論程式碼。The following sections include a discussion of the code.

建立意圖辨識器Create an intent recognizer

辨識語音意圖的第一個步驟,是從 LUIS 端點金鑰和區域建立語音設定。The first step in recognizing intents in speech is to create a speech config from your LUIS endpoint key and region. 語音設定可用來建立語音 SDK 各種功能的辨識器。Speech configs can be used to create recognizers for the various capabilities of the Speech SDK. 語音設定有多種方式可指定您想要使用的訂用帳戶,在此我們使用 FromSubscription,其會採用訂用帳戶金鑰和區域。The speech config has multiple ways to specify the subscription you want to use; here, we use FromSubscription, which takes the subscription key and region.

注意

請使用 LUIS 訂用帳戶 (而非語音服務訂用帳戶) 的金鑰和區域。Use the key and region of your LUIS subscription, not of a Speech Services subscription.

下一步,使用 new IntentRecognizer(config) 建立意圖辨識器。Next, create an intent recognizer using new IntentRecognizer(config). 因為設定已經知道所要使用的訂用帳戶,因此沒有必要在建立辨識器時再次指定訂用帳戶的金鑰和端點。Since the configuration already knows which subscription to use, there's no need to specify the subscription key and endpoint again when creating the recognizer.

匯入 LUIS 模型及新增意圖Import a LUIS model and add intents

現在,使用 LanguageUnderstandingModel.FromAppId() 從 LUIS 應用程式 (app) 匯入模型,並透過辨識器的 AddIntent() 方法新增您想要辨識的 LUIS 意圖。Now import the model from the LUIS app using LanguageUnderstandingModel.FromAppId() and add the LUIS intents that you wish to recognize via the recognizer's AddIntent() method. 這兩個步驟可藉由指出使用者可能會在其要求中使用的字組,來改善語音辨識的精確度。These two steps improve the accuracy of speech recognition by indicating words that the user is likely to use in their requests. 如果您不需要辨識應用程式 (application) 中的所有應用程式 (app) 意圖,則不需要新增所有意圖。It is not necessary to add all the app's intents if you do not need to recognize them all in your application.

新增意圖需要用到三個引數:LUIS 模型 (已建立並命名為 model)、意圖名稱和意圖識別碼。Adding intents requires three arguments: the LUIS model (which has been created and is named model), the intent name, and an intent ID. 識別碼與名稱之間的差異如下。The difference between the ID and the name is as follows.

AddIntent() 引數AddIntent() argument 目的Purpose
intentNameintentName LUIS 應用程式 (app) 中所定義的意圖名稱。The name of the intent as defined in the LUIS app. 必須完全符合 LUIS 意圖名稱。Must match the LUIS intent name exactly.
intentIDintentID 語音 SDK 指派給可辨識意圖的識別碼。An ID assigned to a recognized intent by the Speech SDK. 可以是任何值;不需要對應至 LUIS 應用程式 (app) 中所定義的意圖名稱。Can be whatever you like; does not need to correspond to the intent name as defined in the LUIS app. 舉例來說,如果由相同程式碼處理多個意圖,您可以讓這些意圖使用相同的識別碼。If multiple intents are handled by the same code, for instance, you could use the same ID for them.

「家庭自動化」LUIS 應用程式 (app) 有兩個意圖:一個是要開啟裝置,另一個是要關閉裝置。The Home Automation LUIS app has two intents: one for turning on a device, and another for turning a device off. 下列程式行會將這些意圖新增至辨識器;請將 RecognizeIntentAsync() 方法中的三個 AddIntent 程式行更換為此程式碼。The lines below add these intents to the recognizer; replace the three AddIntent lines in the RecognizeIntentAsync() method with this code.

recognizer.AddIntent(model, "HomeAutomation.TurnOff", "off");
recognizer.AddIntent(model, "HomeAutomation.TurnOn", "on");

您也可以使用 AddAllIntents 方法來將模型中的所有意圖新增至辨識器,而不是新增個別的意圖。Instead of adding individual intents, you can also use the AddAllIntents method to add all the intents in a model to the recognizer.

開始辨識Start recognition

建立辨識器並新增意圖後,就可以開始辨識。With the recognizer created and the intents added, recognition can begin. 語音 SDK 同時支援一次性和連續辨識。The Speech SDK supports both single-shot and continuous recognition.

辨識模式Recognition mode 要呼叫的方法Methods to call 結果Result
一次性Single-shot RecognizeOnceAsync() 在說完一個語句之後傳回可辨識的意圖 (如果有的話)。Returns the recognized intent, if any, after one utterance.
連續Continuous StartContinuousRecognitionAsync()
StopContinuousRecognitionAsync()
辨識多個語句。Recognizes multiple utterances. 有結果時發出事件 (例如 IntermediateResultReceived)。Emits events (e.g. IntermediateResultReceived) when results are available.

教學課程的應用程式 (application) 使用一次性模式,因此會呼叫 RecognizeOnceAsync() 來開始辨識。The tutorial application uses single-shot mode and so calls RecognizeOnceAsync() to begin recognition. 結果是 IntentRecognitionResult 物件,其中包含有關所辨識意圖的資訊。The result is an IntentRecognitionResult object containing information about the intent recognized. 下列運算式會擷取 LUIS JSON 回應:The LUIS JSON response is extracted by the following expression:

result.Properties.GetProperty(PropertyId.LanguageUnderstandingServiceResponse_JsonResult)

教學課程的應用程式 (application) 不會剖析 JSON 結果,只會將結果顯示在主控台視窗中。The tutorial application doesn't parse the JSON result, only displaying it in the console window.

LUIS 辨識結果

指定辨識語言Specify recognition language

根據預設,LUIS 會辨識美式英文 (en-us) 的意圖。By default, LUIS recognizes intents in US English (en-us). 藉由對語音設定的 SpeechRecognitionLanguage 屬性指派地區設定代碼,即可辨識其他語言的意圖。By assigning a locale code to the SpeechRecognitionLanguage property of the speech configuration, you can recognize intents in other languages. 例如,先在教學課程的應用程式 (application) 中新增 config.SpeechRecognitionLanguage = "de-de";,再建立辨識器來辨識德文意圖。For example, add config.SpeechRecognitionLanguage = "de-de"; in our tutorial application before creating the recognizer to recognize intents in German. 請參閱支援的語言See Supported Languages.

從檔案進行連續辨識Continuous recognition from a file

下列程式碼說明兩個使用語音 SDK 來辨識意圖的額外功能。The following code illustrates two additional capabilities of intent recognition using the Speech SDK. 第一個是前面提過的連續辨識,辨識器會在有結果時發出事件。The first, previously mentioned, is continuous recognition, where the recognizer emits events when results are available. 然後,由您提供的事件處理常式處理這些事件。These events can then be processed by event handlers that you provide. 在進行連續辨識時,您會呼叫辨識器的 StartContinuousRecognitionAsync() (而非 RecognizeOnceAsync()) 來開始辨識。With continuous recognition, you call the recognizer's StartContinuousRecognitionAsync() to start recognition instead of RecognizeOnceAsync().

另一個功能是從 WAV 檔案讀取含有所要處理語音的音訊。The other capability is reading the audio containing the speech to be processed from a WAV file. 這牽涉到建立音訊設定以供建立意圖辨識器時使用。This involves creating an audio configuration that can be used when creating the intent recognizer. 檔案必須是取樣率為 16 kHz 的單聲道 (mono)。The file must be single-channel (mono) with a sampling rate of 16 kHz.

若要試用這些功能,請將 RecognizeIntentAsync() 方法的主體更換為下列程式碼。To try out these features, replace the body of the RecognizeIntentAsync() method with the following code.

// Creates an instance of a speech config with specified subscription key
// and service region. Note that in contrast to other services supported by
// the Cognitive Services Speech SDK, the Language Understanding service
// requires a specific subscription key from https://www.luis.ai/.
// The Language Understanding service calls the required key 'endpoint key'.
// Once you've obtained it, replace with below with your own Language Understanding subscription key
// and service region (e.g., "westus").
var config = SpeechConfig.FromSubscription("YourLanguageUnderstandingSubscriptionKey", "YourLanguageUnderstandingServiceRegion");

// Creates an intent recognizer using file as audio input.
// Replace with your own audio file name.
using (var audioInput = AudioConfig.FromWavFileInput("whatstheweatherlike.wav"))
{
    using (var recognizer = new IntentRecognizer(config, audioInput))
    {
        // The TaskCompletionSource to stop recognition.
        var stopRecognition = new TaskCompletionSource<int>();

        // Creates a Language Understanding model using the app id, and adds specific intents from your model
        var model = LanguageUnderstandingModel.FromAppId("YourLanguageUnderstandingAppId");
        recognizer.AddIntent(model, "YourLanguageUnderstandingIntentName1", "id1");
        recognizer.AddIntent(model, "YourLanguageUnderstandingIntentName2", "id2");
        recognizer.AddIntent(model, "YourLanguageUnderstandingIntentName3", "any-IntentId-here");

        // Subscribes to events.
        recognizer.Recognizing += (s, e) => {
            Console.WriteLine($"RECOGNIZING: Text={e.Result.Text}");
        };

        recognizer.Recognized += (s, e) => {
            if (e.Result.Reason == ResultReason.RecognizedIntent)
            {
                Console.WriteLine($"RECOGNIZED: Text={e.Result.Text}");
                Console.WriteLine($"    Intent Id: {e.Result.IntentId}.");
                Console.WriteLine($"    Language Understanding JSON: {e.Result.Properties.GetProperty(PropertyId.LanguageUnderstandingServiceResponse_JsonResult)}.");
            }
            else if (e.Result.Reason == ResultReason.RecognizedSpeech)
            {
                Console.WriteLine($"RECOGNIZED: Text={e.Result.Text}");
                Console.WriteLine($"    Intent not recognized.");
            }
            else if (e.Result.Reason == ResultReason.NoMatch)
            {
                Console.WriteLine($"NOMATCH: Speech could not be recognized.");
            }
        };

        recognizer.Canceled += (s, e) => {
            Console.WriteLine($"CANCELED: Reason={e.Reason}");

            if (e.Reason == CancellationReason.Error)
            {
                Console.WriteLine($"CANCELED: ErrorCode={e.ErrorCode}");
                Console.WriteLine($"CANCELED: ErrorDetails={e.ErrorDetails}");
                Console.WriteLine($"CANCELED: Did you update the subscription info?");
            }

            stopRecognition.TrySetResult(0);
        };

        recognizer.SessionStarted += (s, e) => {
            Console.WriteLine("\n    Session started event.");
        };

        recognizer.SessionStopped += (s, e) => {
            Console.WriteLine("\n    Session stopped event.");
            Console.WriteLine("\nStop recognition.");
            stopRecognition.TrySetResult(0);
        };


        // Starts continuous recognition. Uses StopContinuousRecognitionAsync() to stop recognition.
        Console.WriteLine("Say something...");
        await recognizer.StartContinuousRecognitionAsync().ConfigureAwait(false);

        // Waits for completion.
        // Use Task.WaitAny to keep the task rooted.
        Task.WaitAny(new[] { stopRecognition.Task });

        // Stops recognition.
        await recognizer.StopContinuousRecognitionAsync().ConfigureAwait(false);
    }
}

請修訂程式碼,在其中納入 LUIS 端點金鑰、區域和應用程式 (app) 識別碼,以及如過去一樣新增「家庭自動化」意圖。Revise the code to include your LUIS endpoint key, region, and app ID and to add the Home Automation intents, as before. whatstheweatherlike.wav 變更為音訊檔案的名稱。Change whatstheweatherlike.wav to the name of your audio file. 接著建置和執行。Then build and run.

取得範例Get the samples

如需最新的範例,請參閱 GitHub 上的認知服務語音 SDK 範例程式碼存放庫For the latest samples, see the Cognitive Services Speech SDK sample code repository on GitHub.

在 samples/csharp/sharedcontent/console 資料夾中尋找本文中的程式碼。Look for the code from this article in the samples/csharp/sharedcontent/console folder.

後續步驟Next steps