VoiceManager.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using Windows.Foundation;
  5. using Windows.Media.Playback;
  6. using Windows.Media.SpeechRecognition;
  7. using Windows.Media.SpeechSynthesis;
  8. namespace Urho
  9. {
  10. public class VoiceManager
  11. {
  12. Dictionary<string, Action> cortanaCommands = null;
  13. public SpeechRecognizer SpeechRecognizer { get; private set; }
  14. public SpeechSynthesizer Synthesizer { get; private set; }
  15. public async Task TextToSpeech(string text)
  16. {
  17. if (string.IsNullOrEmpty(text))
  18. return;
  19. if (Synthesizer == null)
  20. Synthesizer = new SpeechSynthesizer();
  21. var tcs = new TaskCompletionSource<bool>();
  22. var stream = await Synthesizer.SynthesizeTextToStreamAsync(text);
  23. var player = BackgroundMediaPlayer.Current;
  24. TypedEventHandler<MediaPlayer, object> mediaEndedHandler = null;
  25. mediaEndedHandler = (s, e) =>
  26. {
  27. tcs.TrySetResult(true);
  28. //subscribe once.
  29. player.MediaEnded -= mediaEndedHandler;
  30. };
  31. player.SetStreamSource(stream);
  32. player.MediaEnded += mediaEndedHandler;
  33. player.Play();
  34. await tcs.Task;
  35. }
  36. public async Task<bool> RegisterCortanaCommands(Dictionary<string, Action> commands)
  37. {
  38. try
  39. {
  40. cortanaCommands = commands;
  41. SpeechRecognizer = new SpeechRecognizer();
  42. var constraint = new SpeechRecognitionListConstraint(cortanaCommands.Keys);
  43. SpeechRecognizer.Constraints.Clear();
  44. SpeechRecognizer.Constraints.Add(constraint);
  45. var result = await SpeechRecognizer.CompileConstraintsAsync();
  46. if (result.Status == SpeechRecognitionResultStatus.Success)
  47. {
  48. SpeechRecognizer.ContinuousRecognitionSession.StartAsync();
  49. SpeechRecognizer.ContinuousRecognitionSession.ResultGenerated += (s, e) =>
  50. {
  51. if (e.Result.RawConfidence >= 0.5f)
  52. {
  53. Action handler;
  54. if (cortanaCommands.TryGetValue(e.Result.Text, out handler))
  55. Application.InvokeOnMain(handler);
  56. }
  57. };
  58. return true;
  59. }
  60. return false;
  61. }
  62. catch (Exception exc)
  63. {
  64. LogSharp.Warn("RegisterCortanaCommands: " + exc);
  65. return false;
  66. }
  67. }
  68. }
  69. }