利用现有的队列进行语音朗读
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Speech.Synthesis; using System.Threading; namespace Utility { public sealed class Sound { private static object obj = new object(); private static Queue<string> speckList; public static void AddToPlay(string content) { if (string.IsNullOrWhiteSpace(content)) return; lock (obj) { if (speckList == null) { speckList = new Queue<string>(); StartProcess(); } speckList.Enqueue(content); } } public static void StartProcess() { Thread speck = new Thread(() => { while (true) { lock (obj) { if (speckList != null && speckList.Count > 0) { sendSound(speckList.Dequeue()); if (speckList.Count == 0) { speckList = null; break; } } } } }); speck.IsBackground = true; speck.Start(); } //保存上次播放的语言 private static string lastString = string.Empty; //保存默认的信息 private static string firstString = string.Empty; public static void SpeckNoRepeate(string sound) { if (string.IsNullOrWhiteSpace(firstString))//第一次赋值 { if (sound.Equals(ConfigHelper.GateInfo.InitialMessage)) { firstString = sound; } } else { if (sound.Equals(firstString)) { return; } sound += " " + sound; } //如果和上一次的信息一致,则取消发送语音,可以避免多次重复刷卡 if (lastString.Equals(sound)) { return; } sendSound(sound); lastString = sound; } private static void sendSound(string sound) { using (SpeechSynthesizer _speaker = new SpeechSynthesizer()) { _speaker.SelectVoiceByHints(VoiceGender.Female); PromptBuilder prompt = new PromptBuilder(); PromptStyle style = new PromptStyle { Rate = PromptRate.Slow, Volume = PromptVolume.ExtraLoud }; prompt.StartStyle(style); prompt.AppendText(Changestring(sound)); prompt.EndStyle(); _speaker.Speak(prompt); } } private static string Changestring(string input) { return input.Replace(" ", "、") .Replace("0", " 零") .Replace("1", " 一") .Replace("2", " 二") .Replace("3", " 三") .Replace("4", " 四") .Replace("5", " 五") .Replace("6", " 六") .Replace("7", " 七") .Replace("8", " 八") .Replace("9", " 九") .Replace("-", "杠") .Replace("A", " A") .Replace("B", " B") .Replace("C", " C") .Replace("D", " D") .Replace("E", " E") .Replace("F", " F") .Replace("G", " G") .Replace("H", " H") .Replace("I", " I") .Replace("J", " J") .Replace("K", " K") .Replace("L", " L") .Replace("M", " M") .Replace("N", " N") .Replace("O", " O") .Replace("P", " P") .Replace("Q", " Q") .Replace("R", " R") .Replace("S", " S") .Replace("T", " T") .Replace("U", " U") .Replace("V", " V") .Replace("W", " W") .Replace("X", " X") .Replace("Y", " Y") .Replace("Z", " Z") .Replace('#', ' ') ; } } }
界面只需调用AddToPlay(string) 方法,即可按顺序进行播放语言。该方法利用序列的先进先出特点。可按顺序即时(但不一定实时,因为语音朗读需要时间)。 当队列为空时就关闭后台进程。