SemanticResultKey Construtores

Definição

Constrói uma instância de SemanticResultKey e associa a chave com componentes de gramática.Constructs an instance of SemanticResultKey and associates the key with grammar components.

Sobrecargas

SemanticResultKey(String, GrammarBuilder[])

Atribui uma chave semântica a um ou mais objetos GrammarBuilder usados para criar uma gramática de reconhecimento de fala.Assigns a semantic key to one or more GrammarBuilder objects used to create a speech recognition grammar.

SemanticResultKey(String, String[])

Atribui uma chave semântica a uma ou mais instâncias de String usadas para criar uma gramática de reconhecimento de fala.Assigns a semantic key to one or more String instances used to create a speech recognition grammar.

Comentários

Os construtores para SemanticResultKey especificar uma marca de texto (a chave semântica) e um conjunto de componentes gramaticais a serem adicionados a uma gramática de reconhecimento de fala.The constructors for SemanticResultKey specify a text tag (the semantic key) and a set of grammar components to add to a speech recognition grammar.

Os componentes de gramática podem ser especificados como uma matriz de GrammarBuilder objetos ou como uma matriz de String instâncias.The grammar components can be specified either as an array of GrammarBuilder objects, or as an array of String instances.

Se os componentes de gramática forem usados no reconhecimento, você poderá acessar o retornado SemanticValue usando a marca de texto fornecida ao construtor de SemanticResultKey como uma chave semântica.If the grammar components are used in recognition, you can access the returned SemanticValue using the text tag provided to the constructor of SemanticResultKey as a semantic key. A Value propriedade da SemanticValue instância será determinada pelos componentes gramaticais usados na definição de SemanticResultKey .The Value property of the SemanticValue instance will be determined by the grammar components used in the definition of SemanticResultKey.

SemanticResultKey(String, GrammarBuilder[])

Atribui uma chave semântica a um ou mais objetos GrammarBuilder usados para criar uma gramática de reconhecimento de fala.Assigns a semantic key to one or more GrammarBuilder objects used to create a speech recognition grammar.

public:
 SemanticResultKey(System::String ^ semanticResultKey, ... cli::array <System::Speech::Recognition::GrammarBuilder ^> ^ builders);
public SemanticResultKey (string semanticResultKey, params System.Speech.Recognition.GrammarBuilder[] builders);
new System.Speech.Recognition.SemanticResultKey : string * System.Speech.Recognition.GrammarBuilder[] -> System.Speech.Recognition.SemanticResultKey
Public Sub New (semanticResultKey As String, ParamArray builders As GrammarBuilder())

Parâmetros

semanticResultKey
String

A marca a ser usada como uma chave semântica para acessar a instância de SemanticValue associada aos objetos GrammarBuilder especificados pelo argumento builders.The tag to be used as a semantic key to access the SemanticValue instance associated with the GrammarBuilder objects specified by the builders argument.

builders
GrammarBuilder[]

Uma matriz de componentes de gramática que será associada a um objeto SemanticValue acessível com a marca definida em semanticResultKey.An array of grammar components that will be associated with a SemanticValue object accessible with the tag defined in semanticResultKey.

Exemplos

O exemplo a seguir cria um Grammar para reconhecer a entrada de senha no formato "minha senha é...", onde a entrada real é correspondida com um curinga.The following example creates a Grammar to recognize password input of the form "My password is …", where the actual input is matched with a wildcard.

O curinga é marcado por um SpeechRecognizer cujo valor de chave é "senha".The wildcard is tagged by a SpeechRecognizer whose key value is "Password". O SpeechRecognized manipulador verifica a presença dessa marca, obtém a entrada de áudio da senha e verifica a senha.The SpeechRecognized handler checks for the presence of this tag, obtains the audio input of the password, and verifies the password.

private void pwdGrammar()   
{  
  GrammarBuilder pwdBuilder = new GrammarBuilder("My Password is");  
  GrammarBuilder wildcardBuilder = new GrammarBuilder();  
  wildcardBuilder.AppendWildcard();  
  SemanticResultKey wildcardKey= new SemanticResultKey("Password", wildcardBuilder);  
  pwdBuilder+=wildcardKey;  
  Grammar grammar = new Grammar(pwdBuilder);  
  grammar.Name = "Password input";  

  grammar.SpeechRecognized +=   
    delegate(object sender, SpeechRecognizedEventArgs eventArgs)   
    {  
      SemanticValue semantics = eventArgs.Result.Semantics;  
      RecognitionResult result=eventArgs.Result;  

      if (!semantics.ContainsKey("Password"))   
      {  
        SpeechUI.SendTextFeedback(eventArgs.Result, "No Password Provided", false);  
      }  
      else   
      {  
        RecognizedAudio pwdAudio = result.GetAudioForWordRange(  
                  result.Words[3],  
                  result.Words[result.Words.Count - 1]);  
                  MemoryStream pwdMemoryStream = new MemoryStream();  
                  pwdAudio.WriteToAudioStream(pwdMemoryStream);  
        if (!IsValidPwd(pwdMemoryStream))   
        {  
          string badPwd = System.IO.Path.GetTempPath() + "BadPwd" + (new Random()).Next().ToString() + ".wav";  
          FileStream waveStream = new FileStream(badPwd, FileMode.Create);    
          pwdAudio.WriteToWaveStream(waveStream);  
          waveStream.Flush();  
          waveStream.Close();  
          SpeechUI.SendTextFeedback(eventArgs.Result, "Invalid Password", false);      
        }  
      }  
    };  

  grammar.Enabled = true;  
  _recognizer.LoadGrammar(grammar);  
  UpdateGrammarTree(_grammarTreeView, _recognizer);  

}  

Comentários

Devido a conversões implícitas, o builders argumento também dá suporte a SemanticResultValue SemanticResultKey objetos,, Choices e String .Because of implicit conversions, the builders argument supports SemanticResultValue, SemanticResultKey, Choices, and String objects as well. Para obter mais informações sobre conversões implícitas, consulte Implicit .For more information on implicit conversions, see Implicit.

Ao executar uma operação de reconhecimento, os GrammarBuilder objetos fornecidos no builders argumento são tratados como sequenciais.When performing a recognition operation, the GrammarBuilder objects provided in the builders argument are treated as sequential. Por exemplo, se o seguinte SemanticResultValue for usado para construir um Grammar , a entrada para o mecanismo de reconhecimento deve conter as palavras "a rápida raposa marrom" em sequência a ser reconhecida.For example, if the following SemanticResultValue is used to construct a Grammar, input to the recognition engine must contain the words "the quick brown fox" in sequence to be recognized.

SemanticResultKey stringTest=new SemanticResultKey(  
    "stringTest", new GrammarBuilder[] {  
    new GrammarBuilder("the"),  
    new GrammarBuilder("quick"),  
    new GrammarBuilder("brown"),  
    new GrammarBuilder("fox")});  

O semanticResultKey argumento contém a marca usada para acessar o SemanticValue que pode ser retornado.The semanticResultKey argument contains the tag used to access the SemanticValue which might be returned.

O Value de SemanticValue é determinado pelas GrammarBuilder instâncias fornecidas pelo builders parâmetro.The Value of the SemanticValue is determined by the GrammarBuilder instances provided by the builders parameter.

Se os GrammarBuilder objetos não contiverem nenhuma instância de definição de SemanticResultValue , o valor de SemanticValue será null .If the GrammarBuilder objects contain no defining instances of SemanticResultValue, the value of the SemanticValue is null.

Se os GrammarBuilder objetos fornecidos no builders parâmetro fornecerem uma instância não marcada (não associada a um SemanticResultKey objeto) SemanticResultValue que é usada pela lógica de reconhecimento, essa instância do SemanticResultValue irá definir a Value Propriedade do SemanticValue que é produzida.If the GrammarBuilder objects provided in the builders parameter provide an untagged (not associated with a SemanticResultKey object) SemanticResultValue instance that is used by the recognition logic, that instance of SemanticResultValue will define the Value property of the SemanticValue that is produced.

Deve haver uma e apenas uma SemanticResultValue instância não marcada nos GrammarBuilder objetos especificados pelo builders parâmetro.There should be one, and only one, untagged SemanticResultValue instance in the GrammarBuilder objects specified by the builders parameter. Se várias instâncias de não marcadas SemanticResultValue estiverem associadas ao SemanticResultKey , cada uma tentará definir o valor do SemanticValue produzido no resultado do reconhecimento.If multiple instances of untagged SemanticResultValue are associated with the SemanticResultKey, each will attempt to the set the value of the SemanticValue produced in the recognition result. Isso não é permitido e o reconhecedor irá gerar uma exceção quando tentar usar um Grammar criado usando uma instância desse tipo SemanticResultKey .This is not permitted, and the recognizer will generate an exception when it attempts to use a Grammar created using such a SemanticResultKey instance.

As instâncias do SemanticResultValue contidas nos GrammarBuilder objetos especificados pelo builders parâmetro e já associadas a outro SemanticResultKey não têm nenhum efeito na SemanticResultKey instância atual.Instances of SemanticResultValue contained in the GrammarBuilder objects specified by the builders parameter and already associated with another SemanticResultKey have no effect on the current SemanticResultKey instance.

Aplica-se a

SemanticResultKey(String, String[])

Atribui uma chave semântica a uma ou mais instâncias de String usadas para criar uma gramática de reconhecimento de fala.Assigns a semantic key to one or more String instances used to create a speech recognition grammar.

public:
 SemanticResultKey(System::String ^ semanticResultKey, ... cli::array <System::String ^> ^ phrases);
public SemanticResultKey (string semanticResultKey, params string[] phrases);
new System.Speech.Recognition.SemanticResultKey : string * string[] -> System.Speech.Recognition.SemanticResultKey
Public Sub New (semanticResultKey As String, ParamArray phrases As String())

Parâmetros

semanticResultKey
String

A marca a ser usada para acessar a instância de SemanticValue associada aos objetos String especificados pelo argumento phrases.The tag to be used access the SemanticValue instance associated with the String objects specified by the phrases argument.

phrases
String[]

Um ou mais objetos String, cujo texto concatenado será associado a um objeto SemanticValue acessível com a marca definida em semanticResultKey.One or more String objects, whose concatenated text will be associated with a SemanticValue object accessible with the tag defined in semanticResultKey.

Exemplos

O exemplo a seguir cria um Grammar de um GrammarBuilder objeto que usa um SemanticResultKey , que é definido por uma matriz de String objetos.The following example creates a Grammar from a GrammarBuilder object that uses a SemanticResultKey, which is defined by an array of String objects.

Um mecanismo de reconhecimento usando o Grammar criado reconhecerá a frase "cor vermelha verde azul zero".A recognition engine using the Grammar created will recognize the phrase "color red green blue zero". A semântica do RecognizedPhrase retornado pelo reconhecimento conterá um SemanticValue com um Value "vermelho verde azul".The semantics of the RecognizedPhrase returned by recognition will contain a SemanticValue with a Value of "red green blue". Você pode acessar o SemanticValue usando a marca "código".You can access the SemanticValue using the "code" tag.

Devido à SemanticResultValue("zero", 5) anexação ao GrammarBuilder , o SemanticValue objeto raiz no RecognizedPhrase terá um valor de 5.Because of the SemanticResultValue("zero", 5) appended to the GrammarBuilder, the root SemanticValue object in the RecognizedPhrase will have a value of 5.

private void keyTest()   
{  
  // Say "color red green blue zero"  
  GrammarBuilder gb = new GrammarBuilder("color") +  
                        new SemanticResultKey("code",   
                          (new string[] {"red", "green", "blue"})) +  
                        new SemanticResultValue("zero", 5);  
  Grammar g = new Grammar(gb);  
  g.Name = "keyTest";  
  _recognizer.LoadGrammar(g);  
}  

Comentários

Ao executar uma operação de reconhecimento, os String objetos usados no phrases parâmetro são tratados como sequenciais.When performing a recognition operation, the String objects used in the phrases parameter are treated as sequential. Por exemplo, se o seguinte SemanticResultValue for usado para construir um Grammar , a entrada para o mecanismo de reconhecimento deve conter as palavras "a rápida raposa marrom" em sequência a ser reconhecida.For example, if the following SemanticResultValue is used to construct a Grammar, input to the recognition engine must contain the words "the quick brown fox" in sequence to be recognized.

SemanticResultKey stringTest=new SemanticResultKey("stringTest",   
                                new string[] {  
                                               "the",  
                                               "quick",  
                                               "brown",  
                                               "fox"});  

O semanticResultKey argumento determina a chave usada para acessar o SemanticValue que pode ser retornado.The semanticResultKey argument determines the key used to access the SemanticValue which might be returned.

Se você construir um Grammar usando um GrammarBuilder objeto que contém uma chave semântica com uma matriz de objetos de cadeia de caracteres, o Value de SemanticValue produzido por uma operação de reconhecimento será a cadeia de caracteres usada no reconhecimento.If you construct a Grammar using a GrammarBuilder object that contains a semantic key with an array of string objects, the Value of the SemanticValue produced by a recognition operation will be the string used in recognition. No exemplo anterior, isso significa que Value seria "a rápida raposa marrom".In the preceding example, this means that Value would be "the quick brown fox".

Aplica-se a