Brak opisu

TtsHelper.cs 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Speech.AudioFormat;
  6. using System.Speech.Synthesis;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using System.Web;
  11. using CallCenter.Utility.Common;
  12. using SpeechLib;
  13. namespace CallCenter.Utility
  14. {
  15. public class TtsHelper
  16. {
  17. public static string GetAudioPath(string text, string name = "")
  18. {
  19. if (!string.IsNullOrEmpty(text))
  20. {
  21. name = string.IsNullOrEmpty(name) ? CommonHelper.MD5(text) : name + "-" + CommonHelper.MD5(text);
  22. string filename = name + ".wav";
  23. string path = HttpContext.Current.Server.MapPath("..") + "\\Audio\\";
  24. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  25. string pathfile = path + filename;
  26. if (!File.Exists(pathfile))
  27. {
  28. File.Create(pathfile).Dispose();
  29. Task.Factory.StartNew(() =>
  30. {
  31. SpeechSynthesizer synth = new SpeechSynthesizer();
  32. SpeechAudioFormatInfo wavFromat = new SpeechAudioFormatInfo(EncodingFormat.Pcm, 1024 * 11, 16, 1, 16000, 2, null);
  33. synth.SetOutputToWaveFile(pathfile, wavFromat);
  34. synth.Speak(text);
  35. synth.SetOutputToNull();
  36. });
  37. }
  38. return pathfile;
  39. }
  40. else
  41. {
  42. return "";
  43. }
  44. }
  45. public static string GetAudioPath1(string text)
  46. {
  47. if (!string.IsNullOrEmpty(text))
  48. {
  49. string filename = CommonHelper.MD5(text) + ".wav";
  50. string path = HttpContext.Current.Server.MapPath("..") + "\\Audio\\";
  51. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  52. string pathfile = path + filename;
  53. if (!File.Exists(pathfile))
  54. {
  55. SpFileStream stream = new SpFileStream();
  56. stream.Open(pathfile, SpeechStreamFileMode.SSFMCreateForWrite, false);
  57. SpVoice sv = new SpVoice();
  58. sv.AudioOutputStream = stream;
  59. sv.Speak(text);
  60. sv.WaitUntilDone(Timeout.Infinite);
  61. stream.Close();
  62. }
  63. return pathfile;
  64. }
  65. else
  66. {
  67. return "";
  68. }
  69. }
  70. }
  71. }