Maneira inteligente de lidar com comandos de voz no código para ação de um comando
Em vez de usar verificações de Switch / Case ou IF Boolean que podem ficar muito longas e terrivelmente tediosas, pergunto-me se é possível procurar uma maneira melhor de manipular e processar Comandos.
POR EXEMPLO:
if(settings.getName == Command)
{
Speak("I am here");
}
if("Get News Feed" == Command)
{
MyRSSFeed RSSNewsFeed = new MyRSSFeed();
RSSNewsFeed.GetFeed();
}
Os comandos if continuam ... Aqui está um trecho da minha instrução de troca:
switch (Command)
{
#region <-- Get Time Command -->
case "Time Please":
case "Whats the Time":
case "What Time is it":
GetCurrentTime();
break;
#endregion <-- Get Time Command -->
#region <-- Get Date Command -->
case "Whats the Date":
case "What Date is it":
case "Whats the Date Today":
case "What is the Date Today":
GetCurrentDate();
break;
#endregion <-- Get Date Command -->
#region <-- Media Player Commands -->
case "Play Bamboo Forest":
Data.MusicPlayer.Play(@"\Bamboo Forest Play List.wpl");
break;
case "Next Song":
Data.MusicPlayer.Next();
break;
case "Previous Song":
Data.MusicPlayer.Previous();
break;
case "Stop Music":
Data.MusicPlayer.Stop();
break;
case "Pause Music":
Data.MusicPlayer.Pause();
break;
case "Resume Music":
Data.MusicPlayer.Resume();
break;
case "Mute Music":
Data.MusicPlayer.Mute();
break;
case "Volume Up":
Data.MusicPlayer.VolumeUp();
break;
case "Volume Down":
Data.MusicPlayer.VolumeDown();
break;
#endregion <-- Media Player Commands -->
#region <-- Voice Recognition Control Commands -->
case "Stop Listening":
Audio.Listen.NewCommandRecognitionEngine.RecognizeAsyncCancel();
Audio.Voice.Speak("Ok");
Audio.Listen.Initialise(main);
break;
#endregion <-- Voice Recognition Control Commands -->
#region <-- Application Commands -->
case "Quiet":
Audio.Voice.Stop();
break;
case "Download":
Audio.Voice.Speak("Opening Download Window.");
main.dlInterface.ShowBitsJobs();
break;
case "Settings":
Audio.Voice.Speak("Opening Settings Window.");
main.settings.Show();
break;
case "Close":
if (main.dlInterface.Visable == true)
{
main.dlInterface.Hide();
Audio.Voice.Speak("Closing Download Window.");
}
if (main.settings.Visible == true)
{
main.settings.Hide();
Audio.Voice.Speak("Closing Settings Window.");
}
break;
case "Out of the way":
if (main.WindowState == System.Windows.Forms.FormWindowState.Normal)
{
main.WindowState = System.Windows.Forms.FormWindowState.Minimized;
Audio.Voice.Speak("My apologies");
}
break;
case "Where Are You":
if (main.WindowState == System.Windows.Forms.FormWindowState.Minimized)
{
main.WindowState = System.Windows.Forms.FormWindowState.Normal;
Audio.Voice.Speak("Here");
}
break;
default:
// Do Nothing here...
break;
}
Eu tenho um banco de dados SQL que contém comandos. Eu carrego comandos nele como preciso. Tem um nome de comando Colum e um valor Colum. Eu posso alterá-los para adicionar alterações ou excluir colunas conforme necessário.
Atualmente, uma vez que um comando é reconhecido, eu uso uma combinação de instruções IF e um Switch / Case Catch para capturar o comando reconhecido.
Eu tenho pensado sobre de alguma forma, soltando dll em uma pasta e alguns como digitalização, em seguida, no carregamento do aplicativo. Se eu adicionar um comando, use de alguma forma o campo de valor para executar o comando na dll.
Eu percebo que esta é uma situação bastante complexa, mas eu sinto que uma solução muito melhor pode ser encontrada para tornar esse processo muito mais simples.
EDIT: eu olhei para isso já:http://social.msdn.microsoft.com/Forums/pt-BR/4f962dc0-aec2-4191-9fe2-e1dfeb1da5dd/voice-command-api
Por favor, pergunte se você precisar de mais alguma informação.
[EDITAR] Paqogomez respondeu a esta pergunta. Veja meu exemplo de trabalho abaixo:
using System;
using System.Linq;
using MyApp.AppCommands;
using System.Reflection;
using System.Collections.Generic;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
MethodInfo myMethod;
var methods = new Commands();
myMethod = CommandFactory.GetCommandMethods("Time Please");
myMethod.Invoke(methods, null);
myMethod = CommandFactory.GetCommandMethods("Volume Down");
myMethod.Invoke(methods, null);
myMethod = CommandFactory.GetCommandMethods("Volume Up");
myMethod.Invoke(methods, null);
Console.ReadLine();
}
}
public static class CommandFactory
{
private static Dictionary<string, MethodInfo> commandMethods = new Dictionary<string, MethodInfo>();
public static MethodInfo GetCommandMethods(string Command)
{
MethodInfo methodInfo;
var myCommandMethods = new Commands();
if (commandMethods.Count == 0)
{
var methodNames = typeof(Commands).GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
var speechAttributeMethods = methodNames.Where(y => y.GetCustomAttributes().OfType<CommandAttribute>().Any());
foreach (var speechAttributeMethod in speechAttributeMethods)
{
foreach (var attribute in speechAttributeMethod.GetCustomAttributes(true))
{
commandMethods.Add(((CommandAttribute)attribute).CommandValue, speechAttributeMethod);
}
}
methodInfo = commandMethods[Command];
}
else
{
methodInfo = commandMethods[Command];
}
return methodInfo;
}
}
}
namespace MyApp.AppCommands
{
public class Commands
{
[Command("Time Please")]
[Command("Whats the Time")]
[Command("What Time is it")]
public void GetTime()
{
Console.WriteLine(DateTime.Now.ToLocalTime());
}
[Command("Volume Down")]
public void VolumeDown()
{
Console.WriteLine("Volume Down 1");
}
[Command("Volume Up")]
public void VolumeUp()
{
Console.WriteLine("Volume Up 1");
}
}
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = true)]
public class CommandAttribute : System.Attribute
{
public string CommandValue { get; set; }
public CommandAttribute(string textValue)
{
this.CommandValue = textValue;
}
}
}
Belo trabalho Paqogomez e obrigado por compartilhar! Isso é rápido e muito elegante!
No meu caso, tudo que eu preciso chamar o código é:
private static void CommandRecognized(object sender, SpeechRecognizedEventArgs e)
{
MethodInfo myMethod;
var methods = new Commands();
myMethod = CommandFactory.GetCommandMethods(e.Result.Text);
myMethod.Invoke(methods, null);
}
que é o manipulador de eventos do mecanismo de reconhecimento de fala:
CommandRecognitionEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(CommandRecognized);