微軟小娜開發教程

利用語音指令通過Cortana開啓前臺應用


利用語音指令除了能打開系統應用之外,還能打開前臺應用並在應用內指定執行的操作或命令。

1、定義語音指令文件

新建一個空的UWP應用,往工程中添加一個空的XML文件。
語音指令特指在VCD(voice command definition)文件中按照一定格式定義的詞語組合。
舉個栗子,這個VCD文件是一個名叫“Adventure Works”的工程下的一個XML文件:

<?xml version="1.0" encoding="utf-8"?>
<VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.1">
  <CommandSet xml:lang="en-us" Name="AdventureWorksCommandSet_en-us">
    <CommandPrefix> Adventure Works, </CommandPrefix>
    <Example> 顯示倫敦之行 </Example>

    <Command Name="showTripToDestination">
      <Example> 顯示倫敦之行  </Example>
      <ListenFor> 顯示去 {destination} 的旅行</ListenFor>
      <Feedback> 正在顯示去 {destination} 的旅行</Feedback>
      <Navigate/>
    </Command>

    <PhraseList Label="destination">
      <Item> 倫敦</Item>
      <Item> 紐約</Item>
      <Item> 北京</Item>
    </PhraseList>

    <PhraseTopic Label="newDestination" Scenario="Search">
      <Subject>City/State</Subject>
    </PhraseTopic>
  </CommandSet>

<!-- Other CommandSets for other languages -->
</VoiceCommands>

這個XML文件裏就定義了一個語音命令”Adventure Works,顯示去倫敦的旅行“。這裏

的語音指令很靈活,可以在PhraseList 標籤中動態添加。
VCD文件動態添加指令指南

2、安裝VCD命令

當應用激活時,需要在OnLaunched處理程序中調用InstallCommandDefinitionsFromStorageFileAsync以註冊系統應該偵聽的命令。
在App.xaml.cs文件下的Onlaunched函數中添加如下代碼段

.......
Window.Current.Activate();
            try
            {
                var storageFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(
                    new Uri("ms-appx:///VoiceCommands.xml"));
                await
                    Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinitionManager.
                    InstallCommandDefinitionsFromStorageFileAsync(storageFile);
            }
            catch (Exception)
            {

                throw;
            }

處理激活並執行語音命令

安裝語音指令集後,指定應用如何響應後續指定操作或指令動作。例如,你的應用可能導航到特定頁的內容、顯示地圖或說出確認語句等。
執行語音指令的操作,是最終最終願景。需要在重寫OnActivated()函數裏幹三件事:
1. 確認你的應用已經通過語音命令激活。
2. 確認命令名稱和說出的內容。
3. 執行動作,通常是導航到相關頁面。

這裏寫代碼片
protected override void OnActivated(IActivatedEventArgs e)
{
  // Was the app activated by a voice command?
  if (e.Kind != Windows.ApplicationModel.Activation.ActivationKind.VoiceCommand)
  {
    return;
  }

  var commandArgs = e as Windows.ApplicationModel.Activation.VoiceCommandActivatedEventArgs;

  Windows.ApplicationModel.VoiceCommands.VoiceCommand.SpeechRecognitionResult speechRecognitionResult = 
    commandArgs.Result;

  // Get the name of the voice command and the text spoken
  string voiceCommandName = speechRecognitionResult.RulePath[0];
  string textSpoken = speechRecognitionResult.Text;
  // The commandMode is either "voice" or "text", and it indicates how the voice command was entered by the user.
  // Apps should respect "text" mode by providing feedback in a silent form.
  string commandMode = this.SemanticInterpretation("commandMode", speechRecognitionResult);

  switch (voiceCommandName)
  {
    case "showTripToDestination":
    // Access the value of the {destination} phrase in the voice command
    string destination = speechRecognitionResult.SemanticInterpretation.Properties["destination"][0];
    // Create a navigation parameter string to pass to the page
    navigationParameterString = string.Format("{0}|{1}|{2}|{3}", 
                    voiceCommandName, commandMode, textSpoken, destination);
    // Set the page where to navigate for this voice command
    navigateToPageType = typeof(TripPage);
    break;

    default:
      // There is no match for the voice command name. Navigate to MainPage
      navigateToPageType = typeof(MainPage);
      break;
  }
  if (this.rootFrame == null)
  {
    // App needs to create a new Frame, not shown
  }

  if (!this.rootFrame.Navigate(navigateToPageType, navigationParameterString))
    {
    throw new Exception("Failed to create voice command page");
    }
}

到此爲止,一個簡單的通過小娜來開啓前臺的應用就完成了。
下面提供兩個實用例程,源文件可下載。
1、通過小娜來開啓一個簡單的前臺應用
2、Cortana語音命令實例–MSDN_demo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章