你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:通过语音服务和 LUIS 识别意向

重要

LUIS 将于 2025 年 10 月 1 日停用。 自 2023 年 4 月 1 日起,无法创建新的 LUIS 资源。 我们建议迁移 LUIS 应用程序对话语言理解,以便获得持续的产品支持和多语言功能并从中受益。

对话语言理解 (CLU) 适用于具有语音 SDK 1.25 或更高版本的 C# 和 C++。 请参阅快速入门,了解如何使用语音 SDK 和 CLU 识别意向。

参考文档 | 包 (NuGet) | GitHub 上的其他示例

在此快速入门中,你将使用语音 SDK和语言理解 (LUIS) 服务来识别从麦克风获取的音频数据中的意向。 具体来说,你将使用语音 SDK 来捕获语音,并使用 LUIS 中的预构建域来识别主自动化的意向,比如打开和关闭电灯。

先决条件

  • Azure 订阅 - 免费创建订阅
  • 在 Azure 门户中创建语言资源。 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。 这次不需要语音资源。
  • 获取语言资源密钥和区域。 部署语言资源后,选择“转到资源”以查看和管理密钥。 有关 Azure AI 服务资源的详细信息,请参阅获取资源密钥

创建 LUIS 应用以进行意向识别

若要完成意向识别快速入门,需要使用 LUIS 预览门户创建 LUIS 帐户和项目。 本快速入门要求在意向识别可用的区域的 LUIS 订阅。 无需语音服务订阅。

你需要做的第一件事是使用 LUIS 预览门户创建 LUIS 帐户和应用。 创建的 LUIS 应用会将预生成域用于主自动化,提供意向、实体和示例言语。 完成本教程后,你会有一个在云中运行的 LUIS 终结点,可使用语音 SDK 进行调用。

可以按照这些说明创建 LUIS 应用:

完成后,需要以下四项信息:

  • 在打开“语音启动”的情况下重新发布
  • 你的 LUIS 主密钥
  • 你的 LUIS 位置
  • 你的 LUIS 应用 ID

可以在 LUIS 预览门户中从以下位置找到此信息:

  1. 在LUIS 预览门户中,选择你的应用,然后选择“发布”按钮。

  2. 选择“生产”槽,如果使用的是 en-US,请选择“更改设置”,然后将“语音启动”选项切换到“开”位置 。 然后选择“发布”按钮。

    重要

    强烈建议使用“语音启动”,因为它会提高语音识别的准确性。

    Publish LUIS to endpoint

  3. 在 LUIS 预览版门户中,选择“管理”,然后选择“Azure 资源”。 在此页面上,可以找到 LUIS 预测资源的 LUIS 密钥和位置(有时也称为“区域”)。

    LUIS key and location

  4. 获取密钥和位置后,需要应用 ID。 选择“设置”。 此页面上提供应用 ID。

    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 Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。

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

此示例使用 FromSubscription() 方法来生成 SpeechConfig。 有关可用方法的完整列表,请参阅 SpeechConfig 类

语音 SDK 将默认使用 en-us 作为语言进行识别。若要了解如何选择源语言,请参阅如何识别语音

初始化 IntentRecognizer

现在,让我们创建 IntentRecognizer。 此对象是在 using 语句中创建的,以确保正确释放非托管资源。 将此代码插入语音配置下的 RecognizeIntentAsync() 方法。

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

添加 LanguageUnderstandingModel 和意向

需要将 LanguageUnderstandingModel 与意向识别器相关联,并添加要识别的意向。 我们将使用预生成的域中的意向进行主自动化。 将此代码插入到上一部分中的 using 语句。 请确保将 "YourLanguageUnderstandingAppId" 替换为 LUIS 应用 ID。

提示

如果需要查找此值的帮助,请参阅创建 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. 开始识别 - 它将提示你说英语短语。 语音将发送到语音服务,转录为文本,并在控制台中呈现。

参考文档 | 包 (NuGet) | GitHub 上的其他示例

在此快速入门中,你将使用语音 SDK和语言理解 (LUIS) 服务来识别从麦克风获取的音频数据中的意向。 具体来说,你将使用语音 SDK 来捕获语音,并使用 LUIS 中的预构建域来识别主自动化的意向,比如打开和关闭电灯。

先决条件

  • Azure 订阅 - 免费创建订阅
  • 在 Azure 门户中创建语言资源。 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。 这次不需要语音资源。
  • 获取语言资源密钥和区域。 部署语言资源后,选择“转到资源”以查看和管理密钥。 有关 Azure AI 服务资源的详细信息,请参阅获取资源密钥

创建 LUIS 应用以进行意向识别

若要完成意向识别快速入门,需要使用 LUIS 预览门户创建 LUIS 帐户和项目。 本快速入门要求在意向识别可用的区域的 LUIS 订阅。 无需语音服务订阅。

你需要做的第一件事是使用 LUIS 预览门户创建 LUIS 帐户和应用。 创建的 LUIS 应用会将预生成域用于主自动化,提供意向、实体和示例言语。 完成本教程后,你会有一个在云中运行的 LUIS 终结点,可使用语音 SDK 进行调用。

可以按照这些说明创建 LUIS 应用:

完成后,需要以下四项信息:

  • 在打开“语音启动”的情况下重新发布
  • 你的 LUIS 主密钥
  • 你的 LUIS 位置
  • 你的 LUIS 应用 ID

可以在 LUIS 预览门户中从以下位置找到此信息:

  1. 在LUIS 预览门户中,选择你的应用,然后选择“发布”按钮。

  2. 选择“生产”槽,如果使用的是 en-US,请选择“更改设置”,然后将“语音启动”选项切换到“开”位置 。 然后选择“发布”按钮。

    重要

    强烈建议使用“语音启动”,因为它会提高语音识别的准确性。

    Publish LUIS to endpoint

  3. 在 LUIS 预览版门户中,选择“管理”,然后选择“Azure 资源”。 在此页面上,可以找到 LUIS 预测资源的 LUIS 密钥和位置(有时也称为“区域”)。

    LUIS key and location

  4. 获取密钥和位置后,需要应用 ID。 选择“设置”。 此页面上提供应用 ID。

    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 Key Vault。 有关详细信息,请参阅 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 下方。 请确保将 "YourLanguageUnderstandingAppId" 替换为 LUIS 应用 ID。

提示

如果需要查找此值的帮助,请参阅创建 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和语言理解 (LUIS) 服务来识别从麦克风获取的音频数据中的意向。 具体来说,你将使用语音 SDK 来捕获语音,并使用 LUIS 中的预构建域来识别主自动化的意向,比如打开和关闭电灯。

先决条件

  • Azure 订阅 - 免费创建订阅
  • 在 Azure 门户中创建语言资源。 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。 这次不需要语音资源。
  • 获取语言资源密钥和区域。 部署语言资源后,选择“转到资源”以查看和管理密钥。 有关 Azure AI 服务资源的详细信息,请参阅获取资源密钥

你还需要安装适用于开发环境的语音 SDK,并创建一个空示例项目

创建 LUIS 应用以进行意向识别

若要完成意向识别快速入门,需要使用 LUIS 预览门户创建 LUIS 帐户和项目。 本快速入门要求在意向识别可用的区域的 LUIS 订阅。 无需语音服务订阅。

你需要做的第一件事是使用 LUIS 预览门户创建 LUIS 帐户和应用。 创建的 LUIS 应用会将预生成域用于主自动化,提供意向、实体和示例言语。 完成本教程后,你会有一个在云中运行的 LUIS 终结点,可使用语音 SDK 进行调用。

可以按照这些说明创建 LUIS 应用:

完成后,需要以下四项信息:

  • 在打开“语音启动”的情况下重新发布
  • 你的 LUIS 主密钥
  • 你的 LUIS 位置
  • 你的 LUIS 应用 ID

可以在 LUIS 预览门户中从以下位置找到此信息:

  1. 在LUIS 预览门户中,选择你的应用,然后选择“发布”按钮。

  2. 选择“生产”槽,如果使用的是 en-US,请选择“更改设置”,然后将“语音启动”选项切换到“开”位置 。 然后选择“发布”按钮。

    重要

    强烈建议使用“语音启动”,因为它会提高语音识别的准确性。

    Publish LUIS to endpoint

  3. 在 LUIS 预览版门户中,选择“管理”,然后选择“Azure 资源”。 在此页面上,可以找到 LUIS 预测资源的 LUIS 密钥和位置(有时也称为“区域”)。

    LUIS key and location

  4. 获取密钥和位置后,需要应用 ID。 选择“设置”。 此页面上提供应用 ID。

    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 对象。

将此代码插入到 main() 中的 try/catch 块中。 请确保更新以下值:

  • "YourLanguageUnderstandingSubscriptionKey" 替换为 LUIS 预测密钥。
  • "YourLanguageUnderstandingServiceRegion" 替换为 LUIS 位置。 使用区域中的“区域标识符”

提示

如果需要帮助查找这些值,请参阅创建 LUIS 应用以进行意向识别

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 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 下方。 请确保将 "YourLanguageUnderstandingAppId" 替换为 LUIS 应用 ID。

提示

如果需要查找此值的帮助,请参阅创建 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 秒,通过麦克风提供的语音输入将被识别并记录到控制台窗口中。

参考文档 | 包 (npm) | GitHub 上的其他示例 | 库源代码

在此快速入门中,你将使用语音 SDK和语言理解 (LUIS) 服务来识别从麦克风获取的音频数据中的意向。 具体来说,你将使用语音 SDK 来捕获语音,并使用 LUIS 中的预构建域来识别主自动化的意向,比如打开和关闭电灯。

先决条件

  • Azure 订阅 - 免费创建订阅
  • 在 Azure 门户中创建语言资源。 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。 这次不需要语音资源。
  • 获取语言资源密钥和区域。 部署语言资源后,选择“转到资源”以查看和管理密钥。 有关 Azure AI 服务资源的详细信息,请参阅获取资源密钥

你还需要安装适用于开发环境的语音 SDK,并创建一个空示例项目

创建 LUIS 应用以进行意向识别

若要完成意向识别快速入门,需要使用 LUIS 预览门户创建 LUIS 帐户和项目。 本快速入门要求在意向识别可用的区域的 LUIS 订阅。 无需语音服务订阅。

你需要做的第一件事是使用 LUIS 预览门户创建 LUIS 帐户和应用。 创建的 LUIS 应用会将预生成域用于主自动化,提供意向、实体和示例言语。 完成本教程后,你会有一个在云中运行的 LUIS 终结点,可使用语音 SDK 进行调用。

可以按照这些说明创建 LUIS 应用:

完成后,需要以下四项信息:

  • 在打开“语音启动”的情况下重新发布
  • 你的 LUIS 主密钥
  • 你的 LUIS 位置
  • 你的 LUIS 应用 ID

可以在 LUIS 预览门户中从以下位置找到此信息:

  1. 在LUIS 预览门户中,选择你的应用,然后选择“发布”按钮。

  2. 选择“生产”槽,如果使用的是 en-US,请选择“更改设置”,然后将“语音启动”选项切换到“开”位置 。 然后选择“发布”按钮。

    重要

    强烈建议使用“语音启动”,因为它会提高语音识别的准确性。

    Publish LUIS to endpoint

  3. 在 LUIS 预览版门户中,选择“管理”,然后选择“Azure 资源”。 在此页面上,可以找到 LUIS 预测资源的 LUIS 密钥和位置(有时也称为“区域”)。

    LUIS key and location

  4. 获取密钥和位置后,需要应用 ID。 选择“设置”。 此页面上提供应用 ID。

    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 Key Vault。 有关详细信息,请参阅 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/azure/ai-services/speech-service/overview" 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 下方。 请确保将 "YourLanguageUnderstandingAppId" 替换为 LUIS 应用 ID。

        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>

创建令牌源(可选)

如果要在 web 服务器上承载网页,可以为演示应用程序提供令牌源。 这样一来,订阅密钥永远不会离开服务器,并且用户可以在不输入任何授权代码的情况下使用语音功能。

创建名为 token.php 的新文件。 此示例假设 Web 服务器在启用 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 文件或使用你喜欢的 web 浏览器打开 index.html。 它将显示一个简单 GUI,用于输入 LUIS 密钥、LUIS 区域和 LUIS 应用程序 ID。 输入这些字段后,可以单击相应按钮以使用麦克风触发识别。

注意

此方法对 Safari 浏览器不起作用。 在 Safari 上,示例网页需要托管在 Web 服务器上;Safari 不允许从本地文件加载的网站使用麦克风。

通过 web 服务器生成并运行示例

若要启动应用,请打开你最喜欢的 Web 浏览器,将其指向托管文件夹的公共 URL,输入 LUIS 区域以及 LUIS 应用程序 ID,并使用麦克风触发识别。 配置后,它将从令牌源获取令牌并开始识别语音命令。

参考文档 | 包 (PyPi) | GitHub 上的其他示例

在此快速入门中,你将使用语音 SDK和语言理解 (LUIS) 服务来识别从麦克风获取的音频数据中的意向。 具体来说,你将使用语音 SDK 来捕获语音,并使用 LUIS 中的预构建域来识别主自动化的意向,比如打开和关闭电灯。

先决条件

  • Azure 订阅 - 免费创建订阅
  • 在 Azure 门户中创建语言资源。 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。 这次不需要语音资源。
  • 获取语言资源密钥和区域。 部署语言资源后,选择“转到资源”以查看和管理密钥。 有关 Azure AI 服务资源的详细信息,请参阅获取资源密钥

你还需要安装适用于开发环境的语音 SDK,并创建一个空示例项目

创建 LUIS 应用以进行意向识别

若要完成意向识别快速入门,需要使用 LUIS 预览门户创建 LUIS 帐户和项目。 本快速入门要求在意向识别可用的区域的 LUIS 订阅。 无需语音服务订阅。

你需要做的第一件事是使用 LUIS 预览门户创建 LUIS 帐户和应用。 创建的 LUIS 应用会将预生成域用于主自动化,提供意向、实体和示例言语。 完成本教程后,你会有一个在云中运行的 LUIS 终结点,可使用语音 SDK 进行调用。

可以按照这些说明创建 LUIS 应用:

完成后,需要以下四项信息:

  • 在打开“语音启动”的情况下重新发布
  • 你的 LUIS 主密钥
  • 你的 LUIS 位置
  • 你的 LUIS 应用 ID

可以在 LUIS 预览门户中从以下位置找到此信息:

  1. 在LUIS 预览门户中,选择你的应用,然后选择“发布”按钮。

  2. 选择“生产”槽,如果使用的是 en-US,请选择“更改设置”,然后将“语音启动”选项切换到“开”位置 。 然后选择“发布”按钮。

    重要

    强烈建议使用“语音启动”,因为它会提高语音识别的准确性。

    Publish LUIS to endpoint

  3. 在 LUIS 预览版门户中,选择“管理”,然后选择“Azure 资源”。 在此页面上,可以找到 LUIS 预测资源的 LUIS 密钥和位置(有时也称为“区域”)。

    LUIS key and location

  4. 获取密钥和位置后,需要应用 ID。 选择“设置”。 此页面上提供应用 ID。

    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 Key Vault。 有关详细信息,请参阅 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 下方。 请确保将 "YourLanguageUnderstandingAppId" 替换为 LUIS 应用 ID。

提示

如果需要查找此值的帮助,请参阅创建 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 秒,通过麦克风提供的语音输入将被识别并记录到控制台窗口中。

参考文档 | 包 (Go) | GitHub 上的其他示例

适用于 Go 的语音 SDK 不支持意向识别。 请选择其他编程语言,或从本文开头链接的 Go 引用和示例。

参考文档 | 包(下载) | GitHub 上的其他示例

适用于 Objective-C 的语音 SDK 确实支持意向识别,但我们尚未在此处提供相关指南。 请选择其他编程语言开始了解相关概念,或参阅本文开头链接的 Objective-C 引用和示例。

参考文档 | 包(下载) | GitHub 上的其他示例

适用于 Swift 的语音 SDK 确实支持意向识别,但我们尚未在此处提供相关指南。 请选择其他编程语言以开始学习并了解相关概念,或参阅本文开头链接的 Swift 引用和示例。

语音转文本 REST API 参考 | 适用于短音频的语音转文本 REST API 参考 | GitHub 上的其他示例

你可以使用 REST API 进行意向识别,但我们尚未在此处提供相关指南。 请选择其他编程语言以开始学习并了解相关概念。

语音命令行接口 (CLI) 确实支持意向识别,但我们尚未在此处提供相关指南。 请选择其他编程语言以开始学习并了解相关概念,或参阅语音 CLI 概述以了解有关 CLI 的详细信息。

后续步骤