需求:
根据英语单词,语句生成wav文件。
根据文本,生成wav文件。
主要代码:
其实就是一个类,调用的是System.Speech.Synthesis.SpeechSynthesizer类,我们重新包装一下这个类,方便我们自己调用,代码如下:
/// <summary>
/// 文本转语音并保存wav和MP3文件/// </summary>public class MySpeech{ VoiceClass _setViceClass; public MySpeech(VoiceClass setViceClass) { _setViceClass = setViceClass; } private SpeechSynthesizer synth = null; /// <summary> /// 返回一个SpeechSynthesizer对象 /// </summary> /// <returns></returns> private SpeechSynthesizer GetSpeechSynthesizerInstance() { if (synth == null) { synth = new SpeechSynthesizer(); } return synth; } /// <summary> /// 开始朗读 放在线程中 /// </summary> /// <param name="VoiceObject"></param> private void RingVoice(object VoiceObject) { try { VoiceClass voiceClass = (VoiceClass)VoiceObject; synth = GetSpeechSynthesizerInstance(); //synth.SelectVoice(voiceClass.VoiceName); if (_setViceClass.Rate > 0) synth.Rate = _setViceClass.Rate; if (_setViceClass.Volume > 0) synth.Volume = _setViceClass.Volume;synth.SpeakAsync(voiceClass.VoiceText);
} catch (Exception er) { Console.WriteLine(er.ToString()); } } /// <summary> /// 播放 /// </summary> public void Play() { Thread thread = new Thread(RingVoice); thread.Start(_setViceClass); } public void SaveMp3() { try { synth = GetSpeechSynthesizerInstance();//synth.SelectVoice(_setViceClass.VoiceName);
if (_setViceClass.Rate > 0) synth.Rate = _setViceClass.Rate; if (_setViceClass.Volume > 0) synth.Volume = _setViceClass.Volume;string str = System.AppDomain.CurrentDomain.BaseDirectory + "\\" + _setViceClass.VoiceText + ".wav";
synth.SetOutputToWaveFile(str); synth.Speak(_setViceClass.VoiceText); synth.SetOutputToNull(); } catch (Exception er) { Console.WriteLine(er.ToString()); } }}/// <summary>
/// 设置:语速 音量 播放人 播放文本/// </summary>public class VoiceClass{ /// <summary> /// 播放人/// 该操作使用 Windows 2000 和 Windows XP 的旧式 Sam 语音,以及新 Anna 和 Windows Vista 的 Microsoft® Lili 语音。
/// Microsoft Sam /// Microsoft Anna /// Microsoft Lili /// </summary> public string VoiceName { get; set; } /// <summary> /// 语速 /// -10 到 10 /// </summary> public int Rate { get; set; } /// <summary> /// 音量 /// 0 到 100 /// </summary> public int Volume { get; set; } /// <summary> /// 播放文本 /// </summary> public string VoiceText { get; set; }}主要调用:
效果图:
目录:
请先在English.txt中输入你要转换的文本,在打开exe文件如下图:
获取:
下载地址: