VoiceManager.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Speech.Synthesis;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace NEIntelligentControl2.Service.Voice
  9. {
  10. /// <summary>
  11. /// 声音播放管理
  12. /// </summary>
  13. internal class VoiceManager
  14. {
  15. private static readonly object _Locker = new object();
  16. private bool _IsPlayVoice;
  17. private Queue<string> _Tasks;
  18. public VoiceManager()
  19. {
  20. try
  21. {
  22. string pav = System.Configuration.ConfigurationManager.AppSettings["PlayAlarmVoice"];
  23. _IsPlayVoice = pav.ToLower() == "y" || pav.ToLower() == "true";
  24. }
  25. catch { }
  26. _Tasks = new Queue<string>();
  27. Task.Factory.StartNew(PlayVoice, TaskCreationOptions.LongRunning);
  28. }
  29. private void PlayVoice()
  30. {
  31. while (_IsPlayVoice)
  32. {
  33. try
  34. {
  35. lock (_Locker)
  36. {
  37. if (_Tasks.Count <= 0)
  38. {
  39. Monitor.Wait(_Locker);
  40. }
  41. }
  42. using (SpeechSynthesizer ss = new SpeechSynthesizer() { Rate = 1 })
  43. {
  44. ss.SetOutputToDefaultAudioDevice();
  45. var vc = ss.GetInstalledVoices()?.Where(c => c.VoiceInfo?.Culture?.Name == "zh-CN").FirstOrDefault();
  46. if (vc != null)
  47. {
  48. ss.SelectVoice(vc.VoiceInfo.Name);
  49. }
  50. ss.Speak(_Tasks.Dequeue());
  51. }
  52. }
  53. catch (Exception e)
  54. {
  55. Console.WriteLine(e.ToString());
  56. }
  57. Thread.Sleep(1000);
  58. }
  59. }
  60. public void Add(string message)
  61. {
  62. if (string.IsNullOrWhiteSpace(message)) return;
  63. lock (_Locker)
  64. {
  65. _Tasks.Enqueue(message);
  66. Monitor.Pulse(_Locker);
  67. }
  68. }
  69. }
  70. }