日期:2014-05-17 浏览次数:20887 次
using System.Speech.Recognition; namespace Douban { public partial class MainWindow : Window { SpeechRecognizer speechRecognizer; public MainWindow() { InitializeComponent(); // if (Properties.Settings.Default.EnableSpeech) speechRecognizer = new SpeechRecognizer(); } private void window_Loaded(object sender, RoutedEventArgs e) { // if(Properties.Settings.Default.EnableSpeech) VoiceCommand(); } private void VoiceCommand() { RegisterVoiceCommand(VoiceCommand_Close, "退出"); RegisterVoiceCommand(VoiceCommand_Next, "下一首"); RegisterVoiceCommand(VoiceCommand_Minimize, "最小化"); RegisterVoiceCommand(VoiceCommand_Restore, "恢复"); RegisterVoiceCommand(VoiceCommand_Pause, "暂停"); RegisterVoiceCommand(VoiceCommand_Resume, "播放"); } private void VoiceCommand_Resume(object sender, EventArgs e) { if (mediaPlayer.MediaState != MediaState.Play) { if (mediaPlayer.MediaUri != null) { mediaPlayer.Play(); pnlPlayer.SetPlayerStatus(true); } } } private void VoiceCommand_Pause(object sender, EventArgs e) { if (mediaPlayer.MediaState == MediaState.Play) { mediaPlayer.Pause(); pnlPlayer.SetPlayerStatus(false); } } private void VoiceCommand_Close(object sender, EventArgs e) { this.Close(); } private void VoiceCommand_Next(object sender, EventArgs e) { } private void VoiceCommand_Minimize(object sender, EventArgs e) { this.WindowState = WindowState.Minimized; } private void VoiceCommand_Restore(object sender, EventArgs e) { this.WindowState = WindowState.Normal; } private void RegisterVoiceCommand(EventHandler Callback, params string[] Args) { Choices choices = new Choices(); foreach (string arg in Args) { choices.Add(arg); } Grammar grammar = new Grammar(new GrammarBuilder(choices)); grammar.SpeechRecognized += delegate(object sender, SpeechRecognizedEventArgs e) { EventHandler eventHandler = new EventHandler(Callback); Dispatcher.BeginInvoke(eventHandler, sender, e); }; speechRecognizer.LoadGrammarAsync(grammar); }