快速入門:使用語音服務和 LUIS 辨識意圖

重要

LUIS 將於 2025 年 10 月 1 日淘汰。 自 2023 年 4 月 1 日起,您無法建立新的 LUIS 資源。 建議您 將 LUIS 應用程式 移轉至 對話式語言理解 ,以受益於持續的產品支援和多語系功能。

交談語言理解 (CLU) 適用於語音 SDK 版本 1.25 或更新的 C# 和 C++。 請參閱使用語音 SDK 和 CLU 辨識意圖的快速入門

GitHub 上的參考檔 | 套件 (NuGet) | 其他範例

在本快速入門中,您將使用 語音 SDK 和 Language Understanding (LUIS) 服務,從麥克風擷取的音訊數據辨識意圖。 具體而言,您將使用語音 SDK 來擷取語音,以及從 LUIS 預先建置的網域來識別家庭自動化的意圖,例如開啟和關閉光線。

必要條件

  • Azure 訂用帳戶 - 免費建立一個訂用帳戶
  • 在 Azure 入口網站上建立語言資源。 您可以使用免費定價層 (F0) 來試用服務,稍後再升級至生產環境的付費層。 您這次不需要語音資源。
  • 取得語言資源索引鍵和區域。 部署語言資源之後,請選取 [移至資源 ] 以檢視和管理密鑰。 如需 Azure AI 服務資源的詳細資訊,請參閱取得資源的金鑰

建立 LUIS 應用程式以進行意圖辨識

若要完成意圖辨識快速入門,您必須使用 LUIS 預覽入口網站建立 LUIS 帳戶和專案。 本快速入門需要在意圖辨識可供使用區域中的 LUIS 訂用帳戶。 不需要語音服務訂用帳戶。

您需要做的第一件事是使用 LUIS 預覽入口網站建立 LUIS 帳戶和應用程式。 您所建立的 LUIS 應用程式會針對家庭自動化使用預先建置的網域,以提供意圖、實體和範例語句。 當您完成時,您會在雲端中執行 LUIS 端點,您可以使用語音 SDK 呼叫該端點。

請遵循下列指示來建立 LUIS 應用程式:

完成時,您需要四件事:

  • 在開啟語音預備時重新發佈
  • 您的 LUIS 主鍵
  • 您的 LUIS 位置
  • LUIS 應用程式識別碼

您可以在 LUIS 預覽入口網站中找到此資訊:

  1. 從 LUIS 預覽入口網站中,選取您的應用程式,然後選取 [ 發佈] 按鈕。

  2. 如果您使用en-US選取變更設定,請選取 [生產位置],然後將 [語音預備] 選項切換至 [開啟] 位置。 然後選取 [ 發佈] 按鈕。

    重要

    強烈建議使用語音擷取 ,因為它可改善語音辨識精確度。

    Publish LUIS to endpoint

  3. 從 LUIS 預覽入口網站選取 [管理],然後選取 [ Azure 資源]。 在此頁面上,您將找到 LUIS 預測資源的 LUIS 金鑰和位置(有時稱為 區域)。

    LUIS key and location

  4. 取得金鑰和位置之後,您將需要應用程式識別碼。 選取設定。 此頁面提供您的應用程式識別碼。

    LUIS app ID

在 Visual Studio 中開啟您的專案

接下來,在Visual Studio中開啟您的專案。

  1. 啟動 Visual Studio 2019。
  2. 載入您的項目並開啟 Program.cs

從一些重複使用的程式代碼開始

讓我們新增一些可作為專案基本架構的程序代碼。 請注意,您已建立名為 RecognizeIntentAsync()的異步方法。

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

namespace helloworld
{
    class Program
    {
        public static async Task RecognizeIntentAsync()
        {
        }

        static async Task Main()
        {
            await RecognizeIntentAsync();
            Console.WriteLine("Please press <Return> to continue.");
            Console.ReadLine();
        }
    }
}

建立語音設定

您必須先建立組態,以使用 LUIS 預測資源的金鑰和位置,才能初始化 IntentRecognizer 物件。

重要

您的入門金鑰和撰寫金鑰將無法運作。 您必須使用您稍早建立的預測金鑰和位置。 如需詳細資訊,請參閱 建立 LUIS 應用程式以進行意圖辨識

在方法中 RecognizeIntentAsync() 插入此程序代碼。 請確定您更新這些值:

  • 將取代 "YourLanguageUnderstandingSubscriptionKey" 為您的 LUIS 預測金鑰。
  • 將取代 "YourLanguageUnderstandingServiceRegion" 為您的 LUIS 位置。 使用來自區域的區域標識碼

提示

如果您需要尋找這些值的協助,請參閱 建立 LUIS 應用程式以進行意圖辨識

重要

當您完成時,請記得從程式碼中移除密鑰,且絕不會公開發佈。 針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 Azure 金鑰保存庫。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

var config = SpeechConfig.FromSubscription(
    "YourLanguageUnderstandingSubscriptionKey",
    "YourLanguageUnderstandingServiceRegion");

這個範例會 FromSubscription() 使用 方法來建置 SpeechConfig。 如需可用方法的完整清單,請參閱 SpeechConfig 類別

語音 SDK 預設會針對語言使用 en-us 辨識,如需選擇來源語言的相關信息,請參閱 如何辨識語音

初始化 IntentRecognizer

現在,讓我們建立 IntentRecognizer。 此物件是在 using 語句內建立,以確保適當的 Unmanaged 資源釋放。 在方法中 RecognizeIntentAsync() ,於語音設定正下方插入此程序代碼。

// Creates an intent recognizer using microphone as audio input.
using (var recognizer = new IntentRecognizer(config))
{
}

新增 LanguageUnderstandingModel 和意圖

您必須將 與意圖辨識器產生關聯 LanguageUnderstandingModel ,並新增您想要辨識的意圖。 我們將使用預先建置網域中的意圖進行家庭自動化。 在上一節的using語句中插入此程序代碼。 請確定您以 LUIS 應用程式識別碼取代 "YourLanguageUnderstandingAppId"

提示

如果您需要尋找此值的協助,請參閱 建立 LUIS 應用程式以進行意圖辨識

// 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");

此範例會使用函 AddIntent() 式個別新增意圖。 如果您想要從模型新增所有意圖,請使用 AddAllIntents(model) 並傳遞模型。

辨識意圖

IntentRecognizer從物件中,您將呼叫 RecognizeOnceAsync() 方法。 這個方法可讓語音服務知道您要傳送單一片語以進行辨識,而且一旦識別片語即可停止辨識語音。

在using語句內,在模型下方新增此程序代碼。

// 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();

顯示辨識結果 (或錯誤)

語音服務傳回辨識結果時,您會想要使用它執行一些動作。 我們將保持簡單,並將結果列印至控制台。

在using語句中,於下方 RecognizeOnceAsync()新增下列程序代碼:

// Checks result.
switch (result.Reason)
{
    case ResultReason.RecognizedIntent:
        Console.WriteLine($"RECOGNIZED: Text={result.Text}");
        Console.WriteLine($"    Intent Id: {result.IntentId}.");
        var json = result.Properties.GetProperty(PropertyId.LanguageUnderstandingServiceResponse_JsonResult);
        Console.WriteLine($"    Language Understanding JSON: {json}.");
        break;
    case ResultReason.RecognizedSpeech:
        Console.WriteLine($"RECOGNIZED: Text={result.Text}");
        Console.WriteLine($"    Intent not recognized.");
        break;
    case ResultReason.NoMatch:
        Console.WriteLine($"NOMATCH: Speech could not be recognized.");
        break;
    case 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?");
        }
        break;
}

檢查您的程序代碼

此時,您的程式代碼看起來應該像這樣:

注意

我們已在此版本中新增一些批注。

//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//

// <skeleton_1>
using System;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Intent;

namespace helloworld
{
    class Program
    {
        public static async Task RecognizeIntentAsync()
        {
            // </skeleton_1>
            // 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".
            // <create_speech_configuration>
            var config = SpeechConfig.FromSubscription(
                "YourLanguageUnderstandingSubscriptionKey",
                "YourLanguageUnderstandingServiceRegion");
            // </create_speech_configuration>

            // <create_intent_recognizer_1>
            // Creates an intent recognizer using microphone as audio input.
            using (var recognizer = new IntentRecognizer(config))
            {
                // </create_intent_recognizer_1>

                // <add_intents>
                // 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");
                // </add_intents>

                // To add all of the possible intents from a LUIS model to the recognizer, uncomment the line below:
                // recognizer.AddAllIntents(model);

                // <recognize_intent>
                // 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();
                // </recognize_intent>

                // <print_results>
                // Checks result.
                switch (result.Reason)
                {
                    case ResultReason.RecognizedIntent:
                        Console.WriteLine($"RECOGNIZED: Text={result.Text}");
                        Console.WriteLine($"    Intent Id: {result.IntentId}.");
                        var json = result.Properties.GetProperty(PropertyId.LanguageUnderstandingServiceResponse_JsonResult);
                        Console.WriteLine($"    Language Understanding JSON: {json}.");
                        break;
                    case ResultReason.RecognizedSpeech:
                        Console.WriteLine($"RECOGNIZED: Text={result.Text}");
                        Console.WriteLine($"    Intent not recognized.");
                        break;
                    case ResultReason.NoMatch:
                        Console.WriteLine($"NOMATCH: Speech could not be recognized.");
                        break;
                    case 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?");
                        }
                        break;
                }
                // </print_results>
            // <create_intent_recognizer_2>
            }
            // </create_intent_recognizer_2>
        // <skeleton_2>
        }

        static async Task Main()
        {
            await RecognizeIntentAsync();
            Console.WriteLine("Please press <Return> to continue.");
            Console.ReadLine();
        }
    }
}
// </skeleton_2>

建置並執行您的應用程式

現在您已準備好建置您的應用程式,並使用語音服務測試我們的語音辨識。

  1. 編譯程式代碼 - 從 Visual Studio 的功能表欄,選擇 [建>置方案]。
  2. 啟動您的應用程式 - 從功能表列,選擇 [>偵錯開始偵錯] 或按 F5。
  3. 開始辨識 - 它會提示您用英文說一個片語。 您的語音會傳送至語音服務、轉譯為文字,並在控制台中轉譯。

GitHub 上的參考檔 | 套件 (NuGet) | 其他範例

在本快速入門中,您將使用 語音 SDK 和 Language Understanding (LUIS) 服務,從麥克風擷取的音訊數據辨識意圖。 具體而言,您將使用語音 SDK 來擷取語音,以及從 LUIS 預先建置的網域來識別家庭自動化的意圖,例如開啟和關閉光線。

必要條件

  • Azure 訂用帳戶 - 免費建立一個訂用帳戶
  • 在 Azure 入口網站上建立語言資源。 您可以使用免費定價層 (F0) 來試用服務,稍後再升級至生產環境的付費層。 您這次不需要語音資源。
  • 取得語言資源索引鍵和區域。 部署語言資源之後,請選取 [移至資源 ] 以檢視和管理密鑰。 如需 Azure AI 服務資源的詳細資訊,請參閱取得資源的金鑰

建立 LUIS 應用程式以進行意圖辨識

若要完成意圖辨識快速入門,您必須使用 LUIS 預覽入口網站建立 LUIS 帳戶和專案。 本快速入門需要在意圖辨識可供使用區域中的 LUIS 訂用帳戶。 不需要語音服務訂用帳戶。

您需要做的第一件事是使用 LUIS 預覽入口網站建立 LUIS 帳戶和應用程式。 您所建立的 LUIS 應用程式會針對家庭自動化使用預先建置的網域,以提供意圖、實體和範例語句。 當您完成時,您會在雲端中執行 LUIS 端點,您可以使用語音 SDK 呼叫該端點。

請遵循下列指示來建立 LUIS 應用程式:

完成時,您需要四件事:

  • 在開啟語音預備時重新發佈
  • 您的 LUIS 主鍵
  • 您的 LUIS 位置
  • LUIS 應用程式識別碼

您可以在 LUIS 預覽入口網站中找到此資訊:

  1. 從 LUIS 預覽入口網站中,選取您的應用程式,然後選取 [ 發佈] 按鈕。

  2. 如果您使用en-US選取變更設定,請選取 [生產位置],然後將 [語音預備] 選項切換至 [開啟] 位置。 然後選取 [ 發佈] 按鈕。

    重要

    強烈建議使用語音擷取 ,因為它可改善語音辨識精確度。

    Publish LUIS to endpoint

  3. 從 LUIS 預覽入口網站選取 [管理],然後選取 [ Azure 資源]。 在此頁面上,您將找到 LUIS 預測資源的 LUIS 金鑰和位置(有時稱為 區域)。

    LUIS key and location

  4. 取得金鑰和位置之後,您將需要應用程式識別碼。 選取設定。 此頁面提供您的應用程式識別碼。

    LUIS app ID

在 Visual Studio 中開啟您的專案

接下來,在Visual Studio中開啟您的專案。

  1. 啟動 Visual Studio 2019。
  2. 載入您的項目並開啟 helloworld.cpp

從一些重複使用的程式代碼開始

讓我們新增一些可作為專案基本架構的程序代碼。 請注意,您已建立名為 recognizeIntent()的異步方法。

#include "stdafx.h"
#include <iostream>
#include <speechapi_cxx.h>

using namespace std;
using namespace Microsoft::CognitiveServices::Speech;
using namespace Microsoft::CognitiveServices::Speech::Intent;

void recognizeIntent()
{
}

int wmain()
{
    try
    {
        recognizeIntent();
    }
    catch (exception e)
    {
        cout << e.what();
    }
    cout << "Please press a key to continue.\n";
    cin.get();
    return 0;
}

建立語音設定

您必須先建立組態,以使用 LUIS 預測資源的金鑰和位置,才能初始化 IntentRecognizer 物件。

重要

您的入門金鑰和撰寫金鑰將無法運作。 您必須使用您稍早建立的預測金鑰和位置。 如需詳細資訊,請參閱 建立 LUIS 應用程式以進行意圖辨識

在方法中 recognizeIntent() 插入此程序代碼。 請確定您更新這些值:

  • 將取代 "YourLanguageUnderstandingSubscriptionKey" 為您的 LUIS 預測金鑰。
  • 將取代 "YourLanguageUnderstandingServiceRegion" 為您的 LUIS 位置。 使用來自區域的區域標識碼

提示

如果您需要尋找這些值的協助,請參閱 建立 LUIS 應用程式以進行意圖辨識

重要

當您完成時,請記得從程式碼中移除密鑰,且絕不會公開發佈。 針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 Azure 金鑰保存庫。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

auto config = SpeechConfig::FromSubscription(
    "YourLanguageUnderstandingSubscriptionKey",
    "YourLanguageUnderstandingServiceRegion");

這個範例會 FromSubscription() 使用 方法來建置 SpeechConfig。 如需可用方法的完整清單,請參閱 SpeechConfig 類別

語音 SDK 預設會針對語言使用 en-us 辨識,如需選擇來源語言的相關信息,請參閱 如何辨識語音

初始化 IntentRecognizer

現在,讓我們建立 IntentRecognizer。 在方法中 recognizeIntent() ,於語音設定正下方插入此程序代碼。

// Creates an intent recognizer using microphone as audio input.
auto recognizer = IntentRecognizer::FromConfig(config);

新增 LanguageUnderstandingModel 和意圖

您必須將 與意圖辨識器產生關聯 LanguageUnderstandingModel ,並新增您想要辨識的意圖。 我們將使用預先建置網域中的意圖進行家庭自動化。

將此程式代碼插入您的 IntentRecognizer下方。 請確定您以 LUIS 應用程式識別碼取代 "YourLanguageUnderstandingAppId"

提示

如果您需要尋找此值的協助,請參閱 建立 LUIS 應用程式以進行意圖辨識

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

此範例會使用函 AddIntent() 式個別新增意圖。 如果您想要從模型新增所有意圖,請使用 AddAllIntents(model) 並傳遞模型。

辨識意圖

IntentRecognizer從物件中,您將呼叫 RecognizeOnceAsync() 方法。 這個方法可讓語音服務知道您要傳送單一片語以進行辨識,而且一旦識別片語即可停止辨識語音。 為了簡單起見,我們將等待未來返回完成。

在您的模型下方插入此程式碼:

cout << "Say something...\n";

// 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.
auto result = recognizer->RecognizeOnceAsync().get();

顯示辨識結果 (或錯誤)

語音服務傳回辨識結果時,您會想要使用它執行一些動作。 我們將保持簡單,並將結果列印至控制台。

在這裡程式代碼下方 auto result = recognizer->RecognizeOnceAsync().get();插入 :

// Checks result.
if (result->Reason == ResultReason::RecognizedIntent)
{
    cout << "RECOGNIZED: Text=" << result->Text << std::endl;
    cout << "  Intent Id: " << result->IntentId << std::endl;
    cout << "  Intent Service JSON: " << result->Properties.GetProperty(PropertyId::LanguageUnderstandingServiceResponse_JsonResult) << std::endl;
}
else if (result->Reason == ResultReason::RecognizedSpeech)
{
    cout << "RECOGNIZED: Text=" << result->Text << " (intent could not be recognized)" << std::endl;
}
else if (result->Reason == ResultReason::NoMatch)
{
    cout << "NOMATCH: Speech could not be recognized." << std::endl;
}
else if (result->Reason == ResultReason::Canceled)
{
    auto cancellation = CancellationDetails::FromResult(result);
    cout << "CANCELED: Reason=" << (int)cancellation->Reason << std::endl;

    if (cancellation->Reason == CancellationReason::Error)
    {
        cout << "CANCELED: ErrorCode=" << (int)cancellation->ErrorCode << std::endl;
        cout << "CANCELED: ErrorDetails=" << cancellation->ErrorDetails << std::endl;
        cout << "CANCELED: Did you update the subscription info?" << std::endl;
    }
}

檢查您的程序代碼

此時,您的程式代碼看起來應該像這樣:

注意

我們已在此版本中新增一些批注。

//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//

// <skeleton_1>
#include "stdafx.h"
#include <iostream>
#include <speechapi_cxx.h>

using namespace std;
using namespace Microsoft::CognitiveServices::Speech;
using namespace Microsoft::CognitiveServices::Speech::Intent;

void recognizeIntent()
{
    // </skeleton_1>
    // 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 recognition language is "en-us".
    // <create_speech_configuration>
    auto config = SpeechConfig::FromSubscription(
        "YourLanguageUnderstandingSubscriptionKey",
        "YourLanguageUnderstandingServiceRegion");
    // </create_speech_configuration>

    // <create_intent_recognizer>
    // Creates an intent recognizer using microphone as audio input.
    auto recognizer = IntentRecognizer::FromConfig(config);
    // </create_intent_recognizer>

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

    // To add all of the possible intents from a LUIS model to the recognizer, uncomment the line below:
    // recognizer->AddAllIntents(model);

    // <recognize_intent>
    cout << "Say something...\n";

    // 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.
    auto result = recognizer->RecognizeOnceAsync().get();
    // </recognize_intent>

    // <print_results>
    // Checks result.
    if (result->Reason == ResultReason::RecognizedIntent)
    {
        cout << "RECOGNIZED: Text=" << result->Text << std::endl;
        cout << "  Intent Id: " << result->IntentId << std::endl;
        cout << "  Intent Service JSON: " << result->Properties.GetProperty(PropertyId::LanguageUnderstandingServiceResponse_JsonResult) << std::endl;
    }
    else if (result->Reason == ResultReason::RecognizedSpeech)
    {
        cout << "RECOGNIZED: Text=" << result->Text << " (intent could not be recognized)" << std::endl;
    }
    else if (result->Reason == ResultReason::NoMatch)
    {
        cout << "NOMATCH: Speech could not be recognized." << std::endl;
    }
    else if (result->Reason == ResultReason::Canceled)
    {
        auto cancellation = CancellationDetails::FromResult(result);
        cout << "CANCELED: Reason=" << (int)cancellation->Reason << std::endl;

        if (cancellation->Reason == CancellationReason::Error)
        {
            cout << "CANCELED: ErrorCode=" << (int)cancellation->ErrorCode << std::endl;
            cout << "CANCELED: ErrorDetails=" << cancellation->ErrorDetails << std::endl;
            cout << "CANCELED: Did you update the subscription info?" << std::endl;
        }
    }
    // </print_results>
    // <skeleton_2>
}

int wmain()
{
    try
    {
        recognizeIntent();
    }
    catch (exception e)
    {
        cout << e.what();
    }
    cout << "Please press a key to continue.\n";
    cin.get();
    return 0;
}
// </skeleton_2>

建置並執行您的應用程式

現在您已準備好建置您的應用程式,並使用語音服務測試我們的語音辨識。

  1. 編譯程式代碼 - 從 Visual Studio 的功能表欄,選擇 [建>置方案]。
  2. 啟動您的應用程式 - 從功能表列,選擇 [>偵錯開始偵錯] 或按 F5。
  3. 開始辨識 - 它會提示您用英文說一個片語。 您的語音會傳送至語音服務、轉譯為文字,並在控制台中轉譯。

GitHub 上的參考檔 | 其他範例

在本快速入門中,您將使用 語音 SDK 和 Language Understanding (LUIS) 服務,從麥克風擷取的音訊數據辨識意圖。 具體而言,您將使用語音 SDK 來擷取語音,以及從 LUIS 預先建置的網域來識別家庭自動化的意圖,例如開啟和關閉光線。

必要條件

  • Azure 訂用帳戶 - 免費建立一個訂用帳戶
  • 在 Azure 入口網站上建立語言資源。 您可以使用免費定價層 (F0) 來試用服務,稍後再升級至生產環境的付費層。 您這次不需要語音資源。
  • 取得語言資源索引鍵和區域。 部署語言資源之後,請選取 [移至資源 ] 以檢視和管理密鑰。 如需 Azure AI 服務資源的詳細資訊,請參閱取得資源的金鑰

您也需要 安裝適用於開發環境的語音 SDK,並建立空的範例專案

建立 LUIS 應用程式以進行意圖辨識

若要完成意圖辨識快速入門,您必須使用 LUIS 預覽入口網站建立 LUIS 帳戶和專案。 本快速入門需要在意圖辨識可供使用區域中的 LUIS 訂用帳戶。 不需要語音服務訂用帳戶。

您需要做的第一件事是使用 LUIS 預覽入口網站建立 LUIS 帳戶和應用程式。 您所建立的 LUIS 應用程式會針對家庭自動化使用預先建置的網域,以提供意圖、實體和範例語句。 當您完成時,您會在雲端中執行 LUIS 端點,您可以使用語音 SDK 呼叫該端點。

請遵循下列指示來建立 LUIS 應用程式:

完成時,您需要四件事:

  • 在開啟語音預備時重新發佈
  • 您的 LUIS 主鍵
  • 您的 LUIS 位置
  • LUIS 應用程式識別碼

您可以在 LUIS 預覽入口網站中找到此資訊:

  1. 從 LUIS 預覽入口網站中,選取您的應用程式,然後選取 [ 發佈] 按鈕。

  2. 如果您使用en-US選取變更設定,請選取 [生產位置],然後將 [語音預備] 選項切換至 [開啟] 位置。 然後選取 [ 發佈] 按鈕。

    重要

    強烈建議使用語音擷取 ,因為它可改善語音辨識精確度。

    Publish LUIS to endpoint

  3. 從 LUIS 預覽入口網站選取 [管理],然後選取 [ Azure 資源]。 在此頁面上,您將找到 LUIS 預測資源的 LUIS 金鑰和位置(有時稱為 區域)。

    LUIS key and location

  4. 取得金鑰和位置之後,您將需要應用程式識別碼。 選取設定。 此頁面提供您的應用程式識別碼。

    LUIS app ID

打開您的專案

  1. 開啟您慣用的 IDE。
  2. 載入您的項目並開啟 Main.java

從一些重複使用的程式代碼開始

讓我們新增一些可作為專案基本架構的程序代碼。

package speechsdk.quickstart;

import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.intent.*;

/**
 * Quickstart: recognize speech using the Speech SDK for Java.
 */
public class Main {

    /**
     * @param args Arguments are ignored in this sample.
     */
    public static void main(String[] args) {
        } catch (Exception ex) {
            System.out.println("Unexpected exception: " + ex.getMessage());

            assert(false);
            System.exit(1);
        }
    }
}

建立語音設定

您必須先建立組態,以使用 LUIS 預測資源的金鑰和位置,才能初始化 IntentRecognizer 物件。

在中的 try / catch 區塊 main()中插入此程式代碼。 請確定您更新這些值:

  • 將取代 "YourLanguageUnderstandingSubscriptionKey" 為您的 LUIS 預測金鑰。
  • 將取代 "YourLanguageUnderstandingServiceRegion" 為您的 LUIS 位置。 使用來自區域的區域標識碼

提示

如果您需要尋找這些值的協助,請參閱 建立 LUIS 應用程式以進行意圖辨識

重要

當您完成時,請記得從程式碼中移除密鑰,且絕不會公開發佈。 針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 Azure 金鑰保存庫。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

// Replace below with with specified subscription key (called 'endpoint key' by the Language Understanding service)
String languageUnderstandingSubscriptionKey = "YourLanguageUnderstandingSubscriptionKey";
// Replace below with your own service region (e.g., "westus").
String languageUnderstandingServiceRegion = "YourLanguageUnderstandingServiceRegion";

// Creates an instance of intent recognizer with a given speech configuration.
// Recognizer is created with the default microphone audio input and default language "en-us".
try (SpeechConfig config = SpeechConfig.fromSubscription(languageUnderstandingSubscriptionKey, languageUnderstandingServiceRegion);

這個範例會 FromSubscription() 使用 方法來建置 SpeechConfig。 如需可用方法的完整清單,請參閱 SpeechConfig 類別

語音 SDK 預設會針對語言使用 en-us 辨識,如需選擇來源語言的相關信息,請參閱 如何辨識語音

初始化 IntentRecognizer

現在,讓我們建立 IntentRecognizer。 將此程式代碼插入語音設定正下方。

IntentRecognizer recognizer = new IntentRecognizer(config)) {

新增 LanguageUnderstandingModel 和意圖

您必須將 與意圖辨識器產生關聯 LanguageUnderstandingModel ,並新增您想要辨識的意圖。 我們將使用預先建置網域中的意圖進行家庭自動化。

將此程式代碼插入您的 IntentRecognizer下方。 請確定您以 LUIS 應用程式識別碼取代 "YourLanguageUnderstandingAppId"

提示

如果您需要尋找此值的協助,請參閱 建立 LUIS 應用程式以進行意圖辨識

// Creates a language understanding model using the app id, and adds specific intents from your model
LanguageUnderstandingModel model = LanguageUnderstandingModel.fromAppId("YourLanguageUnderstandingAppId");
recognizer.addIntent(model, "YourLanguageUnderstandingIntentName1", "id1");
recognizer.addIntent(model, "YourLanguageUnderstandingIntentName2", "id2");
recognizer.addIntent(model, "YourLanguageUnderstandingIntentName3", "any-IntentId-here");

此範例會使用函 addIntent() 式個別新增意圖。 如果您想要從模型新增所有意圖,請使用 addAllIntents(model) 並傳遞模型。

辨識意圖

IntentRecognizer從物件中,您將呼叫 recognizeOnceAsync() 方法。 這個方法可讓語音服務知道您要傳送單一片語以進行辨識,而且一旦識別片語即可停止辨識語音。

在您的模型下方插入此程式碼:

System.out.println("Say something...");

// Starts recognition. It returns when the first utterance has been recognized.
IntentRecognitionResult result = recognizer.recognizeOnceAsync().get();

顯示辨識結果 (或錯誤)

語音服務傳回辨識結果時,您會想要使用它執行一些動作。 我們將保持簡單,並將結果列印至控制台。

將此程式代碼插入至 的呼叫 recognizeOnceAsync()下方。

// Checks result.
if (result.getReason() == ResultReason.RecognizedIntent) {
    System.out.println("RECOGNIZED: Text=" + result.getText());
    System.out.println("    Intent Id: " + result.getIntentId());
    System.out.println("    Intent Service JSON: " + result.getProperties().getProperty(PropertyId.LanguageUnderstandingServiceResponse_JsonResult));
}
else if (result.getReason() == ResultReason.RecognizedSpeech) {
    System.out.println("RECOGNIZED: Text=" + result.getText());
    System.out.println("    Intent not recognized.");
}
else if (result.getReason() == ResultReason.NoMatch) {
    System.out.println("NOMATCH: Speech could not be recognized.");
}
else if (result.getReason() == ResultReason.Canceled) {
    CancellationDetails cancellation = CancellationDetails.fromResult(result);
    System.out.println("CANCELED: Reason=" + cancellation.getReason());

    if (cancellation.getReason() == CancellationReason.Error) {
        System.out.println("CANCELED: ErrorCode=" + cancellation.getErrorCode());
        System.out.println("CANCELED: ErrorDetails=" + cancellation.getErrorDetails());
        System.out.println("CANCELED: Did you update the subscription info?");
    }
}

檢查您的程序代碼

此時,您的程式代碼看起來應該像這樣:

注意

我們已在此版本中新增一些批注。

//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//

// <skeleton_1>
package speechsdk.quickstart;

import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.intent.*;

/**
 * Quickstart: recognize speech using the Speech SDK for Java.
 */
public class Main {

    /**
     * @param args Arguments are ignored in this sample.
     */
    public static void main(String[] args) {
    // </skeleton_1>
        // <create_speech_configuration>
        // Replace below with with specified subscription key (called 'endpoint key' by the Language Understanding service)
        String languageUnderstandingSubscriptionKey = "YourLanguageUnderstandingSubscriptionKey";
        // Replace below with your own service region (e.g., "westus").
        String languageUnderstandingServiceRegion = "YourLanguageUnderstandingServiceRegion";

        // Creates an instance of intent recognizer with a given speech configuration.
        // Recognizer is created with the default microphone audio input and default language "en-us".
        try (SpeechConfig config = SpeechConfig.fromSubscription(languageUnderstandingSubscriptionKey, languageUnderstandingServiceRegion);
        // </create_speech_configuration>
            // <create_intent_recognizer>
            IntentRecognizer recognizer = new IntentRecognizer(config)) {
            // </create_intent_recognizer>

            // <add_intents>
            // Creates a language understanding model using the app id, and adds specific intents from your model
            LanguageUnderstandingModel model = LanguageUnderstandingModel.fromAppId("YourLanguageUnderstandingAppId");
            recognizer.addIntent(model, "YourLanguageUnderstandingIntentName1", "id1");
            recognizer.addIntent(model, "YourLanguageUnderstandingIntentName2", "id2");
            recognizer.addIntent(model, "YourLanguageUnderstandingIntentName3", "any-IntentId-here");
            // </add_intents>

            // To add all of the possible intents from a LUIS model to the recognizer, uncomment the line below:
            // recognizer.addAllIntents(model);

            // <recognize_intent>
            System.out.println("Say something...");

            // Starts recognition. It returns when the first utterance has been recognized.
            IntentRecognitionResult result = recognizer.recognizeOnceAsync().get();
            // </recognize_intent>

            // <print_result>
            // Checks result.
            if (result.getReason() == ResultReason.RecognizedIntent) {
                System.out.println("RECOGNIZED: Text=" + result.getText());
                System.out.println("    Intent Id: " + result.getIntentId());
                System.out.println("    Intent Service JSON: " + result.getProperties().getProperty(PropertyId.LanguageUnderstandingServiceResponse_JsonResult));
            }
            else if (result.getReason() == ResultReason.RecognizedSpeech) {
                System.out.println("RECOGNIZED: Text=" + result.getText());
                System.out.println("    Intent not recognized.");
            }
            else if (result.getReason() == ResultReason.NoMatch) {
                System.out.println("NOMATCH: Speech could not be recognized.");
            }
            else if (result.getReason() == ResultReason.Canceled) {
                CancellationDetails cancellation = CancellationDetails.fromResult(result);
                System.out.println("CANCELED: Reason=" + cancellation.getReason());

                if (cancellation.getReason() == CancellationReason.Error) {
                    System.out.println("CANCELED: ErrorCode=" + cancellation.getErrorCode());
                    System.out.println("CANCELED: ErrorDetails=" + cancellation.getErrorDetails());
                    System.out.println("CANCELED: Did you update the subscription info?");
                }
            }
            // </print_result>
        // <skeleton_2>
        } catch (Exception ex) {
            System.out.println("Unexpected exception: " + ex.getMessage());

            assert(false);
            System.exit(1);
        }
    }
}
// </skeleton_2>

建置並執行您的應用程式

F11,或選取 [執行>偵錯]。 接下來 15 秒的麥克風語音輸入將會辨識並記錄在控制台視窗中。

GitHub Library 原始程式碼上的參考文件 | 套件 (npm) | 其他範例 |

在本快速入門中,您將使用 語音 SDK 和 Language Understanding (LUIS) 服務,從麥克風擷取的音訊數據辨識意圖。 具體而言,您將使用語音 SDK 來擷取語音,以及從 LUIS 預先建置的網域來識別家庭自動化的意圖,例如開啟和關閉光線。

必要條件

  • Azure 訂用帳戶 - 免費建立一個訂用帳戶
  • 在 Azure 入口網站上建立語言資源。 您可以使用免費定價層 (F0) 來試用服務,稍後再升級至生產環境的付費層。 您這次不需要語音資源。
  • 取得語言資源索引鍵和區域。 部署語言資源之後,請選取 [移至資源 ] 以檢視和管理密鑰。 如需 Azure AI 服務資源的詳細資訊,請參閱取得資源的金鑰

您也需要 安裝適用於開發環境的語音 SDK,並建立空的範例專案

建立 LUIS 應用程式以進行意圖辨識

若要完成意圖辨識快速入門,您必須使用 LUIS 預覽入口網站建立 LUIS 帳戶和專案。 本快速入門需要在意圖辨識可供使用區域中的 LUIS 訂用帳戶。 不需要語音服務訂用帳戶。

您需要做的第一件事是使用 LUIS 預覽入口網站建立 LUIS 帳戶和應用程式。 您所建立的 LUIS 應用程式會針對家庭自動化使用預先建置的網域,以提供意圖、實體和範例語句。 當您完成時,您會在雲端中執行 LUIS 端點,您可以使用語音 SDK 呼叫該端點。

請遵循下列指示來建立 LUIS 應用程式:

完成時,您需要四件事:

  • 在開啟語音預備時重新發佈
  • 您的 LUIS 主鍵
  • 您的 LUIS 位置
  • LUIS 應用程式識別碼

您可以在 LUIS 預覽入口網站中找到此資訊:

  1. 從 LUIS 預覽入口網站中,選取您的應用程式,然後選取 [ 發佈] 按鈕。

  2. 如果您使用en-US選取變更設定,請選取 [生產位置],然後將 [語音預備] 選項切換至 [開啟] 位置。 然後選取 [ 發佈] 按鈕。

    重要

    強烈建議使用語音擷取 ,因為它可改善語音辨識精確度。

    Publish LUIS to endpoint

  3. 從 LUIS 預覽入口網站選取 [管理],然後選取 [ Azure 資源]。 在此頁面上,您將找到 LUIS 預測資源的 LUIS 金鑰和位置(有時稱為 區域)。

    LUIS key and location

  4. 取得金鑰和位置之後,您將需要應用程式識別碼。 選取設定。 此頁面提供您的應用程式識別碼。

    LUIS app ID

從一些重複使用的程式代碼開始

讓我們新增一些可作為專案基本架構的程序代碼。

    <!DOCTYPE html>
    <html>
    <head>
    <title>Microsoft Azure AI Speech SDK JavaScript Quickstart</title>
    <meta charset="utf-8" />
    </head>
    <body style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:13px;">
    </body>
    </html>

新增UI元素

現在,我們將新增一些輸入方塊的基本 UI、參考語音 SDK 的 JavaScript,並在可用時擷取授權令牌。

重要

當您完成時,請記得從程式碼中移除密鑰,且絕不會公開發佈。 針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 Azure 金鑰保存庫。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

<body style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:13px;">
  <div id="content" style="display:none">
    <table width="100%">
      <tr>
        <td></td>
        <td><h1 style="font-weight:500;">Microsoft Azure AI Speech SDK JavaScript Quickstart</h1></td>
      </tr>
      <tr>
        <td align="right"><a href="https://learn.microsoft.com~/articles/ai-services/speech-service/get-started" target="_blank">Subscription</a>:</td>
        <td><input id="subscriptionKey" type="text" size="40" value="subscription"></td>
      </tr>
      <tr>
        <td align="right">Region</td>
        <td><input id="serviceRegion" type="text" size="40" value="YourServiceRegion"></td>
      </tr>
      <tr>
        <td align="right">Application ID:</td>
        <td><input id="appId" type="text" size="60" value="YOUR_LANGUAGE_UNDERSTANDING_APP_ID"></td>
      </tr>
      <tr>
        <td></td>
        <td><button id="startIntentRecognizeAsyncButton">Start Intent Recognition</button></td>
      </tr>
      <tr>
        <td align="right" valign="top">Input Text</td>
        <td><textarea id="phraseDiv" style="display: inline-block;width:500px;height:200px"></textarea></td>
      </tr>
      <tr>
        <td align="right" valign="top">Result</td>
        <td><textarea id="statusDiv" style="display: inline-block;width:500px;height:100px"></textarea></td>
      </tr>
    </table>
  </div>

  <script src="microsoft.cognitiveservices.speech.sdk.bundle.js"></script>

  <script>
  // Note: Replace the URL with a valid endpoint to retrieve
  //       authorization tokens for your subscription.
  var authorizationEndpoint = "token.php";

  function RequestAuthorizationToken() {
    if (authorizationEndpoint) {
      var a = new XMLHttpRequest();
      a.open("GET", authorizationEndpoint);
      a.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      a.send("");
      a.onload = function() {
				var token = JSON.parse(atob(this.responseText.split(".")[1]));
				serviceRegion.value = token.region;
				authorizationToken = this.responseText;
				subscriptionKey.disabled = true;
				subscriptionKey.value = "using authorization token (hit F5 to refresh)";
				console.log("Got an authorization token: " + token);
      }
    }
  }
  </script>

  <script>
    // status fields and start button in UI
    var phraseDiv;
    var statusDiv;
    var startIntentRecognizeAsyncButton;

    // subscription key, region, and appId for LUIS services.
    var subscriptionKey, serviceRegion, appId;
    var authorizationToken;
    var SpeechSDK;
    var recognizer;

    document.addEventListener("DOMContentLoaded", function () {
      startIntentRecognizeAsyncButton = document.getElementById("startIntentRecognizeAsyncButton");
      subscriptionKey = document.getElementById("subscriptionKey");
      serviceRegion = document.getElementById("serviceRegion");
      appId = document.getElementById("appId");
      phraseDiv = document.getElementById("phraseDiv");
      statusDiv = document.getElementById("statusDiv");

      startIntentRecognizeAsyncButton.addEventListener("click", function () {
        startIntentRecognizeAsyncButton.disabled = true;
        phraseDiv.innerHTML = "";
        statusDiv.innerHTML = "";
      });

      if (!!window.SpeechSDK) {
        SpeechSDK = window.SpeechSDK;
        startIntentRecognizeAsyncButton.disabled = false;

        document.getElementById('content').style.display = 'block';
        document.getElementById('warning').style.display = 'none';

        // in case we have a function for getting an authorization token, call it.
        if (typeof RequestAuthorizationToken === "function") {
          RequestAuthorizationToken();
        }
      }
    });
  </script>

建立語音設定

您必須先建立使用訂用帳戶密鑰和訂用帳戶區域的組態,才能初始化 SpeechRecognizer 物件。 在方法中 startRecognizeOnceAsyncButton.addEventListener() 插入此程序代碼。

注意

語音 SDK 預設會針對語言使用 en-us 辨識,如需選擇來源語言的相關信息,請參閱 如何辨識語音

        // if we got an authorization token, use the token. Otherwise use the provided subscription key
        var speechConfig;
        if (authorizationToken) {
          speechConfig = SpeechSDK.SpeechConfig.fromAuthorizationToken(authorizationToken, serviceRegion.value);
        } else {
          if (subscriptionKey.value === "" || subscriptionKey.value === "subscription") {
            alert("Please enter your Microsoft Azure AI Speech subscription key!");
            return;
          }
          startIntentRecognizeAsyncButton.disabled = false;
          speechConfig = SpeechSDK.SpeechConfig.fromSubscription(subscriptionKey.value, serviceRegion.value);
        }

        speechConfig.speechRecognitionLanguage = "en-US";

建立音訊組態

現在,您必須建立指向 AudioConfig 輸入裝置的物件。 在方法中 startIntentRecognizeAsyncButton.addEventListener() ,於語音設定正下方插入此程序代碼。

        var audioConfig = SpeechSDK.AudioConfig.fromDefaultMicrophoneInput();

初始化 IntentRecognizer

現在,讓我們使用稍早建立的 SpeechConfigAudioConfig 物件來建立 IntentRecognizer 物件。 在方法中 startIntentRecognizeAsyncButton.addEventListener() 插入此程序代碼。

        recognizer = new SpeechSDK.IntentRecognizer(speechConfig, audioConfig);

新增 LanguageUnderstandingModel 和意圖

您必須將 與意圖辨識器產生關聯 LanguageUnderstandingModel ,並新增您想要辨識的意圖。 我們將使用預先建置網域中的意圖進行家庭自動化。

將此程式代碼插入您的 IntentRecognizer下方。 請確定您以 LUIS 應用程式識別碼取代 "YourLanguageUnderstandingAppId"

        if (appId.value !== "" && appId.value !== "YOUR_LANGUAGE_UNDERSTANDING_APP_ID") {
          var lm = SpeechSDK.LanguageUnderstandingModel.fromAppId(appId.value);

          recognizer.addAllIntents(lm);
        }

注意

語音 SDK 僅支援 LUIS v2.0 端點。 您必須手動修改範例查詢欄位中找到的 v3.0 端點 URL,才能使用 v2.0 URL 模式。 LUIS v2.0 端點一律遵循下列兩種模式之一:

  • https://{AzureResourceName}.cognitiveservices.azure.com/luis/v2.0/apps/{app-id}?subscription-key={subkey}&verbose=true&q=
  • https://{Region}.api.cognitive.microsoft.com/luis/v2.0/apps/{app-id}?subscription-key={subkey}&verbose=true&q=

辨識意圖

IntentRecognizer從物件中,您將呼叫 recognizeOnceAsync() 方法。 這個方法可讓語音服務知道您要傳送單一片語以進行辨識,而且一旦識別片語即可停止辨識語音。

在模型新增專案下方插入此程式碼:

        recognizer.recognizeOnceAsync(
          function (result) {
            window.console.log(result);

            phraseDiv.innerHTML = result.text + "\r\n";

            statusDiv.innerHTML += "(continuation) Reason: " + SpeechSDK.ResultReason[result.reason];
            switch (result.reason) {
              case SpeechSDK.ResultReason.RecognizedSpeech:
                statusDiv.innerHTML += " Text: " + result.text;
                break;
              case SpeechSDK.ResultReason.RecognizedIntent:
                statusDiv.innerHTML += " Text: " + result.text + " IntentId: " + result.intentId;

                // The actual JSON returned from Language Understanding is a bit more complex to get to, but it is available for things like
                // the entity name and type if part of the intent.
                statusDiv.innerHTML += " Intent JSON: " + result.properties.getProperty(SpeechSDK.PropertyId.LanguageUnderstandingServiceResponse_JsonResult);
                phraseDiv.innerHTML += result.properties.getProperty(SpeechSDK.PropertyId.LanguageUnderstandingServiceResponse_JsonResult) + "\r\n";
                break;
              case SpeechSDK.ResultReason.NoMatch:
                var noMatchDetail = SpeechSDK.NoMatchDetails.fromResult(result);
                statusDiv.innerHTML += " NoMatchReason: " + SpeechSDK.NoMatchReason[noMatchDetail.reason];
                break;
              case SpeechSDK.ResultReason.Canceled:
                var cancelDetails = SpeechSDK.CancellationDetails.fromResult(result);
                statusDiv.innerHTML += " CancellationReason: " + SpeechSDK.CancellationReason[cancelDetails.reason];

              if (cancelDetails.reason === SpeechSDK.CancellationReason.Error) {
                statusDiv.innerHTML += ": " + cancelDetails.errorDetails;
              }
            break;
            }
            statusDiv.innerHTML += "\r\n";
            startIntentRecognizeAsyncButton.disabled = false;
          },
          function (err) {
            window.console.log(err);

            phraseDiv.innerHTML += "ERROR: " + err;
            startIntentRecognizeAsyncButton.disabled = false;
          });

檢查您的程序代碼

<!DOCTYPE html>
<html>
<head>
  <title>Microsoft Cognitive Services Speech SDK JavaScript Quickstart</title>
  <meta charset="utf-8" />
</head>
<body style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:13px;">
  <div id="warning">
    <h1 style="font-weight:500;">Speech Recognition Speech SDK not found (microsoft.cognitiveservices.speech.sdk.bundle.js missing).</h1>
  </div>
  
  <div id="content" style="display:none">
    <table width="100%">
      <tr>
        <td></td>
        <td><h1 style="font-weight:500;">Microsoft Cognitive Services Speech SDK JavaScript Quickstart</h1></td>
      </tr>
      <tr>
        <td align="right"><a href="https://docs.microsoft.com/azure/cognitive-services/speech-service/quickstarts/intent-recognition?pivots=programming-language-csharp#create-a-luis-app-for-intent-recognition" target="_blank">LUIS Primary Key</a>:</td>
        <td><input id="subscriptionKey" type="text" size="40" value="subscription"></td>
      </tr>
      <tr>
        <td align="right">LUIS Location</td>
        <td><input id="serviceRegion" type="text" size="40" value="YourServiceRegion"></td>
      </tr>
      <tr>
        <td align="right">LUIS App ID:</td>
        <td><input id="appId" type="text" size="60" value="YOUR_LANGUAGE_UNDERSTANDING_APP_ID"></td>
      </tr>
      <tr>
        <td></td>
        <td><button id="startIntentRecognizeAsyncButton">Start Intent Recognition</button></td>
      </tr>
      <tr>
        <td align="right" valign="top">Input Text</td>
        <td><textarea id="phraseDiv" style="display: inline-block;width:500px;height:200px"></textarea></td>
      </tr>
      <tr>
        <td align="right" valign="top">Result</td>
        <td><textarea id="statusDiv" style="display: inline-block;width:500px;height:100px"></textarea></td>
      </tr>
    </table>
  </div>

  <!-- Speech SDK reference sdk. -->
  <script src="https://aka.ms/csspeech/jsbrowserpackageraw"></script>

  <!-- Speech SDK USAGE -->
  <script>
    // status fields and start button in UI
    var phraseDiv;
    var statusDiv;
    var startIntentRecognizeAsyncButton;

    // subscription key and region for speech services.
    var subscriptionKey, serviceRegion, appId;
    var SpeechSDK;
    var recognizer;

    document.addEventListener("DOMContentLoaded", function () {

      startIntentRecognizeAsyncButton = document.getElementById("startIntentRecognizeAsyncButton");
      subscriptionKey = document.getElementById("subscriptionKey");
      serviceRegion = document.getElementById("serviceRegion");
      appId = document.getElementById("appId");
      phraseDiv = document.getElementById("phraseDiv");
      statusDiv = document.getElementById("statusDiv");

      startIntentRecognizeAsyncButton.addEventListener("click", function () {
        startIntentRecognizeAsyncButton.disabled = true;
        phraseDiv.innerHTML = "";
        statusDiv.innerHTML = "";

        let audioConfig = SpeechSDK.AudioConfig.fromDefaultMicrophoneInput();
        if (subscriptionKey.value === "" || subscriptionKey.value === "subscription") {
          alert("Please enter your Microsoft Cognitive Services Speech subscription key!");
          startIntentRecognizeAsyncButton.disabled = false;
          return;
        }
        var speechConfig = SpeechSDK.SpeechConfig.fromSubscription(subscriptionKey.value, serviceRegion.value);

        speechConfig.speechRecognitionLanguage = "en-US";
        recognizer = new SpeechSDK.IntentRecognizer(speechConfig, audioConfig);

        // Set up a Language Understanding Model from Language Understanding Intelligent Service (LUIS).
        // See https://www.luis.ai/home for more information on LUIS.
        if (appId.value !== "" && appId.value !== "YOUR_LANGUAGE_UNDERSTANDING_APP_ID") {
          var lm = SpeechSDK.LanguageUnderstandingModel.fromAppId(appId.value);

          recognizer.addAllIntents(lm);
        }

        recognizer.recognizeOnceAsync(
          function (result) {
            window.console.log(result);
            phraseDiv.innerHTML = result.text + "\r\n";

            statusDiv.innerHTML += "(continuation) Reason: " + SpeechSDK.ResultReason[result.reason];
            switch (result.reason) {

              case SpeechSDK.ResultReason.RecognizedSpeech:
                statusDiv.innerHTML += " Text: " + result.text;
                break;

              case SpeechSDK.ResultReason.RecognizedIntent:
                statusDiv.innerHTML += " Text: " + result.text + " IntentId: " + result.intentId;

                // The actual JSON returned from Language Understanding is a bit more complex to get to, but it is available for things like
                // the entity name and type if part of the intent.
                statusDiv.innerHTML += " Intent JSON: " + result.properties.getProperty(SpeechSDK.PropertyId.LanguageUnderstandingServiceResponse_JsonResult);
                phraseDiv.innerHTML += result.properties.getProperty(SpeechSDK.PropertyId.LanguageUnderstandingServiceResponse_JsonResult) + "\r\n";
                break;

              case SpeechSDK.ResultReason.NoMatch:
                var noMatchDetail = SpeechSDK.NoMatchDetails.fromResult(result);
                statusDiv.innerHTML += " NoMatchReason: " + SpeechSDK.NoMatchReason[noMatchDetail.reason];
                break;
                
              case SpeechSDK.ResultReason.Canceled:
                var cancelDetails = SpeechSDK.CancellationDetails.fromResult(result);
                statusDiv.innerHTML += " CancellationReason: " + SpeechSDK.CancellationReason[cancelDetails.reason];

                if (cancelDetails.reason === SpeechSDK.CancellationReason.Error) {
                  statusDiv.innerHTML += ": " + cancelDetails.errorDetails;
                }
                break;
            }
            statusDiv.innerHTML += "\r\n";
            startIntentRecognizeAsyncButton.disabled = false;
          },
          function (err) {
            window.console.log(err);

            phraseDiv.innerHTML += "ERROR: " + err;
            startIntentRecognizeAsyncButton.disabled = false;
        });
      });

      if (!!window.SpeechSDK) {
        SpeechSDK = window.SpeechSDK;
        startIntentRecognizeAsyncButton.disabled = false;

        document.getElementById('content').style.display = 'block';
        document.getElementById('warning').style.display = 'none';
      }
    });

  </script>
</body>
</html>

建立權杖來源 (選擇性)

如果您想要在網頁伺服器上裝載網頁,您可以選擇為示範應用程式提供令牌來源。 如此一來,您的訂用帳戶密鑰絕不會離開您的伺服器,同時允許使用者在不輸入任何授權碼的情況下使用語音功能。

建立名為 token.php的新檔案。 在此範例中,我們假設您的網頁伺服器支援已啟用 curl 的 PHP 腳本語言。 輸入下列程式碼:

<?php
header('Access-Control-Allow-Origin: ' . $_SERVER['SERVER_NAME']);

// Replace with your own subscription key and service region (e.g., "westus").
$subscriptionKey = 'YourSubscriptionKey';
$region = 'YourServiceRegion';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://' . $region . '.api.cognitive.microsoft.com/sts/v1.0/issueToken');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Ocp-Apim-Subscription-Key: ' . $subscriptionKey));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch);
?>

注意

授權令牌只有有限的存留期。 這個簡化的範例不會示範如何自動重新整理授權令牌。 身為使用者,您可以手動重載頁面,或按 F5 重新整理。

在本機建置並執行範例

若要啟動應用程式,請按兩下index.html檔案,或使用您慣用的網頁瀏覽器開啟index.html。 它會顯示簡單的 GUI,可讓您輸入 LUIS 金鑰、 LUIS 區域和 LUIS 應用程式識別碼。 輸入這些欄位之後,您可以按兩下適當的按鈕,以使用麥克風觸發辨識。

注意

此方法不適用於Safari瀏覽器。 在Safari上,範例網頁必須裝載於網頁伺服器上;Safari 不允許從本機檔案載入的網站使用麥克風。

透過網頁伺服器建置並執行範例

若要啟動您的應用程式,請開啟您慣用的網頁瀏覽器,並將它指向您裝載資料夾的公用 URL、輸入您的 LUIS 區域 以及 LUIS 應用程式識別碼,並使用麥克風觸發辨識。 如果已設定,它會從令牌來源取得令牌,並開始辨識口語命令。

GitHub 上的參考檔 | 套件 (PyPi) | 其他範例

在本快速入門中,您將使用 語音 SDK 和 Language Understanding (LUIS) 服務,從麥克風擷取的音訊數據辨識意圖。 具體而言,您將使用語音 SDK 來擷取語音,以及從 LUIS 預先建置的網域來識別家庭自動化的意圖,例如開啟和關閉光線。

必要條件

  • Azure 訂用帳戶 - 免費建立一個訂用帳戶
  • 在 Azure 入口網站上建立語言資源。 您可以使用免費定價層 (F0) 來試用服務,稍後再升級至生產環境的付費層。 您這次不需要語音資源。
  • 取得語言資源索引鍵和區域。 部署語言資源之後,請選取 [移至資源 ] 以檢視和管理密鑰。 如需 Azure AI 服務資源的詳細資訊,請參閱取得資源的金鑰

您也需要 安裝適用於開發環境的語音 SDK,並建立空的範例專案

建立 LUIS 應用程式以進行意圖辨識

若要完成意圖辨識快速入門,您必須使用 LUIS 預覽入口網站建立 LUIS 帳戶和專案。 本快速入門需要在意圖辨識可供使用區域中的 LUIS 訂用帳戶。 不需要語音服務訂用帳戶。

您需要做的第一件事是使用 LUIS 預覽入口網站建立 LUIS 帳戶和應用程式。 您所建立的 LUIS 應用程式會針對家庭自動化使用預先建置的網域,以提供意圖、實體和範例語句。 當您完成時,您會在雲端中執行 LUIS 端點,您可以使用語音 SDK 呼叫該端點。

請遵循下列指示來建立 LUIS 應用程式:

完成時,您需要四件事:

  • 在開啟語音預備時重新發佈
  • 您的 LUIS 主鍵
  • 您的 LUIS 位置
  • LUIS 應用程式識別碼

您可以在 LUIS 預覽入口網站中找到此資訊:

  1. 從 LUIS 預覽入口網站中,選取您的應用程式,然後選取 [ 發佈] 按鈕。

  2. 如果您使用en-US選取變更設定,請選取 [生產位置],然後將 [語音預備] 選項切換至 [開啟] 位置。 然後選取 [ 發佈] 按鈕。

    重要

    強烈建議使用語音擷取 ,因為它可改善語音辨識精確度。

    Publish LUIS to endpoint

  3. 從 LUIS 預覽入口網站選取 [管理],然後選取 [ Azure 資源]。 在此頁面上,您將找到 LUIS 預測資源的 LUIS 金鑰和位置(有時稱為 區域)。

    LUIS key and location

  4. 取得金鑰和位置之後,您將需要應用程式識別碼。 選取設定。 此頁面提供您的應用程式識別碼。

    LUIS app ID

打開您的專案

  1. 開啟您慣用的 IDE。
  2. 建立新的專案,並建立名為 quickstart.py的檔案,然後開啟它。

從一些重複使用的程式代碼開始

讓我們新增一些可作為專案基本架構的程序代碼。

import azure.cognitiveservices.speech as speechsdk

print("Say something...")

建立語音設定

您必須先建立組態,以使用 LUIS 預測資源的金鑰和位置,才能初始化 IntentRecognizer 物件。

在中 quickstart.py插入此程序代碼。 請確定您更新這些值:

  • 將取代 "YourLanguageUnderstandingSubscriptionKey" 為您的 LUIS 預測金鑰。
  • 將取代 "YourLanguageUnderstandingServiceRegion" 為您的 LUIS 位置。 使用來自區域的區域標識碼

提示

如果您需要尋找這些值的協助,請參閱 建立 LUIS 應用程式以進行意圖辨識

重要

當您完成時,請記得從程式碼中移除密鑰,且絕不會公開發佈。 針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 Azure 金鑰保存庫。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

# Set up the config for the intent recognizer (remember that this uses the Language Understanding key, not the Speech Services key)!
intent_config = speechsdk.SpeechConfig(
    subscription="YourLanguageUnderstandingSubscriptionKey",
    region="YourLanguageUnderstandingServiceRegion")

此範例會使用 LUIS 金鑰和區域來建構 SpeechConfig 物件。 如需可用方法的完整清單,請參閱 SpeechConfig 類別

語音 SDK 預設會針對語言使用 en-us 辨識,如需選擇來源語言的相關信息,請參閱 如何辨識語音

初始化 IntentRecognizer

現在,讓我們建立 IntentRecognizer。 將此程式代碼插入語音設定正下方。

# Set up the intent recognizer
intent_recognizer = speechsdk.intent.IntentRecognizer(speech_config=intent_config)

新增 LanguageUnderstandingModel 和意圖

您必須將 與意圖辨識器產生關聯 LanguageUnderstandingModel ,並新增您想要辨識的意圖。 我們將使用預先建置網域中的意圖進行家庭自動化。

將此程式代碼插入您的 IntentRecognizer下方。 請確定您以 LUIS 應用程式識別碼取代 "YourLanguageUnderstandingAppId"

提示

如果您需要尋找此值的協助,請參閱 建立 LUIS 應用程式以進行意圖辨識

# set up the intents that are to be recognized. These can be a mix of simple phrases and
# intents specified through a LanguageUnderstanding Model.
model = speechsdk.intent.LanguageUnderstandingModel(app_id="YourLanguageUnderstandingAppId")
intents = [
    (model, "HomeAutomation.TurnOn"),
    (model, "HomeAutomation.TurnOff"),
    ("This is a test.", "test"),
    ("Switch to channel 34.", "34"),
    ("what's the weather like", "weather"),
]
intent_recognizer.add_intents(intents)

此範例會使用函 add_intents() 式來新增明確定義的意圖清單。 如果您想要從模型新增所有意圖,請使用 add_all_intents(model) 並傳遞模型。

辨識意圖

IntentRecognizer從物件中,您將呼叫 recognize_once() 方法。 這個方法可讓語音服務知道您要傳送單一片語以進行辨識,而且一旦識別片語即可停止辨識語音。

將此程式代碼插入模型下方。

intent_result = intent_recognizer.recognize_once()

顯示辨識結果 (或錯誤)

語音服務傳回辨識結果時,您會想要使用它執行一些動作。 我們將保持簡單,並將結果列印至控制台。

在呼叫 recognize_once()下方,新增此程序代碼。

# Check the results
if intent_result.reason == speechsdk.ResultReason.RecognizedIntent:
    print("Recognized: \"{}\" with intent id `{}`".format(intent_result.text, intent_result.intent_id))
elif intent_result.reason == speechsdk.ResultReason.RecognizedSpeech:
    print("Recognized: {}".format(intent_result.text))
elif intent_result.reason == speechsdk.ResultReason.NoMatch:
    print("No speech could be recognized: {}".format(intent_result.no_match_details))
elif intent_result.reason == speechsdk.ResultReason.Canceled:
    print("Intent recognition canceled: {}".format(intent_result.cancellation_details.reason))
    if intent_result.cancellation_details.reason == speechsdk.CancellationReason.Error:
        print("Error details: {}".format(intent_result.cancellation_details.error_details))

檢查您的程序代碼

此時,您的程式代碼看起來應該像這樣。

注意

我們已在此版本中新增一些批注。

# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root for full license information.

# <skeleton>
import azure.cognitiveservices.speech as speechsdk

print("Say something...")
# </skeleton>

"""performs one-shot intent recognition from input from the default microphone"""

# <create_speech_configuration>
# Set up the config for the intent recognizer (remember that this uses the Language Understanding key, not the Speech Services key)!
intent_config = speechsdk.SpeechConfig(
    subscription="YourLanguageUnderstandingSubscriptionKey",
    region="YourLanguageUnderstandingServiceRegion")
# </create_speech_configuration>

# <create_intent_recognizer>
# Set up the intent recognizer
intent_recognizer = speechsdk.intent.IntentRecognizer(speech_config=intent_config)
# </create_intent_recognizer>

# <add_intents>
# set up the intents that are to be recognized. These can be a mix of simple phrases and
# intents specified through a LanguageUnderstanding Model.
model = speechsdk.intent.LanguageUnderstandingModel(app_id="YourLanguageUnderstandingAppId")
intents = [
    (model, "HomeAutomation.TurnOn"),
    (model, "HomeAutomation.TurnOff"),
    ("This is a test.", "test"),
    ("Switch to channel 34.", "34"),
    ("what's the weather like", "weather"),
]
intent_recognizer.add_intents(intents)
# </add_intents>

# To add all of the possible intents from a LUIS model to the recognizer, uncomment the line below:
# intent_recognizer.add_all_intents(model)

# 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. It returns the recognition text as result.
# Note: Since recognize_once() returns only a single utterance, it is suitable only for single
# shot recognition like command or query.
# For long-running multi-utterance recognition, use start_continuous_recognition() instead.
# <recognize_intent>
intent_result = intent_recognizer.recognize_once()
# </recognize_intent>

# <print_results>
# Check the results
if intent_result.reason == speechsdk.ResultReason.RecognizedIntent:
    print("Recognized: \"{}\" with intent id `{}`".format(intent_result.text, intent_result.intent_id))
elif intent_result.reason == speechsdk.ResultReason.RecognizedSpeech:
    print("Recognized: {}".format(intent_result.text))
elif intent_result.reason == speechsdk.ResultReason.NoMatch:
    print("No speech could be recognized: {}".format(intent_result.no_match_details))
elif intent_result.reason == speechsdk.ResultReason.Canceled:
    print("Intent recognition canceled: {}".format(intent_result.cancellation_details.reason))
    if intent_result.cancellation_details.reason == speechsdk.CancellationReason.Error:
        print("Error details: {}".format(intent_result.cancellation_details.error_details))
# </print_results>

建置並執行您的應用程式

從主控台或在 IDE 中執行範例:

python quickstart.py

接下來 15 秒的麥克風語音輸入將會辨識並記錄在控制台視窗中。

GitHub 上的參考檔 | 套件 (Go) | 其他範例

語音 SDK for Go 不支援意圖辨識。 請從本文開頭選取另一種程式設計語言或 Go 參考和範例。

GitHub 上的參考檔 | 套件 (下載) | 其他範例

適用於 Objective-C 的語音 SDK 支援意圖辨識,但我們尚未在此包含指南。 請選取另一種程式設計語言來開始使用並瞭解概念,或參閱本文開頭連結的 Objective-C 參考和範例。

GitHub 上的參考檔 | 套件 (下載) | 其他範例

適用於 Swift 的語音 SDK 支援意圖辨識,但我們尚未在此包含指南。 請選取另一種程式設計語言來開始使用並瞭解概念,或參閱本文開頭連結的 Swift 參考和範例。

語音轉換文字 REST API 參考 | 適用於簡短音訊的語音轉換文字 REST API 參考 | GitHub 上的其他範例

您可以使用 REST API 進行意圖辨識,但我們尚未在此包含指南。 請選取另一種程式設計語言,以開始使用並瞭解概念。

語音命令行介面 (CLI) 支援意圖辨識,但我們尚未在此包含指南。 請選取其他程式設計語言以開始使用並瞭解概念,或如需 CLI 的詳細資訊,請參閱 語音 CLI 概觀

下一步