|
- using Microsoft.CognitiveServices.Speech;
- using Microsoft.CognitiveServices.Speech.Audio;
- using System;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading.Tasks;
- using System.IO;
- using System.Diagnostics;
-
- namespace BPASmartClient.Device
- {
- public class Speech
- {
- public static uint SND_ASYNC = 0x0001;
- public static uint SND_FILENAME = 0x0002;
-
- [DllImport("winmm.dll", CharSet = CharSet.Auto)]
- public static extern int mciSendString(string m_strCmd, string m_strReceive, int m_v1, int m_v2);
-
- [DllImport("Kernel32", CharSet = CharSet.Auto)]
- public static extern Int32 GetShortPathName(string path, StringBuilder shortPath, Int32 shortPathLength);
-
- private volatile static Speech _Instance;
- public static Speech GetInstance => _Instance ?? (_Instance = new Speech());
- private Speech() { }
-
- /// <summary>
- /// 播放语音
- /// </summary>
- /// <param name="SpeakText"></param>
- public void Speak(string SpeakText)
- {
- string path = $"{AppDomain.CurrentDomain.BaseDirectory}Sound";//设置音频文件保存路径
- Directory.CreateDirectory(path);
- string SpeakPath = $"{path}\\{SpeakText}.wav";
- SpeakPath = SpeakPath.Replace(' ', '_');
- if (!File.Exists(SpeakPath))
- {
- var res = SynthesizeAudioAsync(SpeakText, SpeakPath);
- }
- StringBuilder shortPath = new StringBuilder(200);
- int result = GetShortPathName(SpeakPath, shortPath, shortPath.Capacity);
- string shortName = shortPath.ToString();
- mciSendString(@"close all", null, 0, 0);
- mciSendString(@"open " + shortName + " alias song", null, 0, 0);
- mciSendString(@"play song", null, 0, 0);
- //return "22";
- }
-
- /// <summary>
- /// 文字转音频
- /// </summary>
- /// <param name="text"></param>
- /// <returns></returns>
- private string SynthesizeAudioAsync(string text, string path)
- {
- var config = SpeechConfig.FromSubscription("b88f6907c8f64075a6169dc4d7dff65a", "chinanorth2");
- config.SpeechSynthesisLanguage = "zh-CN"; //config.SpeechSynthesisVoiceName = "";
- using var audioConfig = AudioConfig.FromWavFileOutput(path);
- using var synthesizer = new SpeechSynthesizer(config, audioConfig);
- synthesizer.SpeakTextAsync(text).Wait();
- //await Task.Delay(TimeSpan.FromSeconds(2));
- return "1";
- }
-
-
- }
-
-
-
-
- }
|