usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Speech.Synthesis;usingSystem.Threading;namespaceUtility
{public sealed classSound
{private static object obj = new object();private static QueuespeckList;public static void AddToPlay(stringcontent)
{if (string.IsNullOrWhiteSpace(content))return;lock(obj)
{if (speckList == null)
{
speckList= new Queue();
StartProcess();
}
speckList.Enqueue(content);
}
}public static voidStartProcess()
{
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(stringsound)
{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(stringsound)
{using (SpeechSynthesizer _speaker = newSpeechSynthesizer())
{
_speaker.SelectVoiceByHints(VoiceGender.Female);
PromptBuilder prompt= newPromptBuilder();
PromptStyle style= newPromptStyle
{
Rate=PromptRate.Slow,
Volume=PromptVolume.ExtraLoud
};
prompt.StartStyle(style);
prompt.AppendText(Changestring(sound));
prompt.EndStyle();
_speaker.Speak(prompt);
}
}private static string Changestring(stringinput)
{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('#', ' ')
;
}
}
}