终端一体化运控平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

73 line
2.6 KiB

  1. using Microsoft.CognitiveServices.Speech;
  2. using Microsoft.CognitiveServices.Speech.Audio;
  3. using System;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.IO;
  8. using System.Diagnostics;
  9. namespace BPASmartClient.Device
  10. {
  11. public class Speech
  12. {
  13. public static uint SND_ASYNC = 0x0001;
  14. public static uint SND_FILENAME = 0x0002;
  15. [DllImport("winmm.dll", CharSet = CharSet.Auto)]
  16. public static extern int mciSendString(string m_strCmd, string m_strReceive, int m_v1, int m_v2);
  17. [DllImport("Kernel32", CharSet = CharSet.Auto)]
  18. public static extern Int32 GetShortPathName(string path, StringBuilder shortPath, Int32 shortPathLength);
  19. private volatile static Speech _Instance;
  20. public static Speech GetInstance => _Instance ?? (_Instance = new Speech());
  21. private Speech() { }
  22. /// <summary>
  23. /// 播放语音
  24. /// </summary>
  25. /// <param name="SpeakText"></param>
  26. public void Speak(string SpeakText)
  27. {
  28. string path = $"{AppDomain.CurrentDomain.BaseDirectory}Sound";//设置音频文件保存路径
  29. Directory.CreateDirectory(path);
  30. string SpeakPath = $"{path}\\{SpeakText}.wav";
  31. SpeakPath = SpeakPath.Replace(' ', '_');
  32. if (!File.Exists(SpeakPath))
  33. {
  34. var res = SynthesizeAudioAsync(SpeakText, SpeakPath);
  35. }
  36. StringBuilder shortPath = new StringBuilder(200);
  37. int result = GetShortPathName(SpeakPath, shortPath, shortPath.Capacity);
  38. string shortName = shortPath.ToString();
  39. mciSendString(@"close all", null, 0, 0);
  40. mciSendString(@"open " + shortName + " alias song", null, 0, 0);
  41. mciSendString(@"play song", null, 0, 0);
  42. //return "22";
  43. }
  44. /// <summary>
  45. /// 文字转音频
  46. /// </summary>
  47. /// <param name="text"></param>
  48. /// <returns></returns>
  49. private string SynthesizeAudioAsync(string text, string path)
  50. {
  51. var config = SpeechConfig.FromSubscription("b88f6907c8f64075a6169dc4d7dff65a", "chinanorth2");
  52. config.SpeechSynthesisLanguage = "zh-CN"; //config.SpeechSynthesisVoiceName = "";
  53. using var audioConfig = AudioConfig.FromWavFileOutput(path);
  54. using var synthesizer = new SpeechSynthesizer(config, audioConfig);
  55. synthesizer.SpeakTextAsync(text).Wait();
  56. //await Task.Delay(TimeSpan.FromSeconds(2));
  57. return "1";
  58. }
  59. }
  60. }