Skip to content

Instantly share code, notes, and snippets.

@mikebuss
Created January 25, 2020 19:29
Show Gist options
  • Save mikebuss/510fa1e1803d246edf2657115b5ce4ff to your computer and use it in GitHub Desktop.
Save mikebuss/510fa1e1803d246edf2657115b5ce4ff to your computer and use it in GitHub Desktop.
PhraseRecognitionExample
using System.Collections.Generic;
using UnityEngine.Windows.Speech;
using System.Linq;
public class PhraseRecognitionExample : MonoBehaviour
{
// Holds all of the keywords and their actions
Dictionary<string, System.Action> keywords = new Dictionary<string, System.Action>();
// Called before the first frame update
void Start()
{
keywords.Add("start", () =>
{
// Perform this action if the user says Start
});
keywords.Add("stop", () =>
{
// Perform this action if the user says Stop
});
keywords.Add("help", () =>
{
// Perform this action if the user says Help
});
KeywordRecognizer keywordRecognizer;
keywordRecognizer = new KeywordRecognizer(keywords.Keys.ToArray());
keywordRecognizer.OnPhraseRecognized += KeywordRecognizer_OnPhraseRecognized;
keywordRecognizer.Start();
}
private void KeywordRecognizer_OnPhraseRecognized(PhraseRecognizedEventArgs args)
{
System.Action keywordAction;
if (keywords.TryGetValue(args.text, out keywordAction))
{
// If the spoken keyword was one we subscribed to,
// log the match and perform the action we associated with it in Start()
System.Diagnostics.Debug.WriteLine("Recognized keyword: " + args.text);
keywordAction.Invoke();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment