一、在Visual Studio中新建一个控制台项目。

二、添加对System.Speech.dll的引用。
三、调用合成的API。
using System;
using System.Speech.Synthesis;
using System.Speech.AudioFormat;
namespace CSharpTTS
{
/// <summary>
/// 使用微软Speech.dll进行语言合成
/// 在引用中添加对system.Speech的引用
/// </summary>
class Program
{
/// <summary>
/// 接收两个启动参数 args[0]文件名称 args[1]要进行语音转换的文字
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
if (args.Length > 1)
{
get(args[0],args[1]);
}
else
Console.WriteLine("没有输入值");
//Console.WriteLine("按任意键退出");
//Console.ReadKey();
}
//生成wav文件
public static void get(string fileName,string text)
{
try
{
if (text.Length > 65535)
{
Console.WriteLine("文字长度太长了,请将文字控制在65535个字符之内!");
return;
}
string filePath = Environment.CurrentDirectory+ $"\\speech\\{fileName}.wav";
if (System.IO.File.Exists(filePath))
{
Console.WriteLine("语音存在了!");
return;
}
else
{
using (SpeechSynthesizer synth = new SpeechSynthesizer())
{
synth.SetOutputToWaveFile(filePath, new SpeechAudioFormatInfo(32000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
PromptBuilder builder = new PromptBuilder();
builder.AppendText(text);
synth.Speak(builder);
}
Console.WriteLine("生成语音成功!");
}
}
catch (Exception e)
{
Console.WriteLine("生成语音失败了!"+e);
}
}
/// <summary>
/// 使用系统默认播放器播放合成后的声音
/// </summary>
/// <param name="text"></param>
private static void Speek(string text)
{
var speaker = new SpeechSynthesizer();
speaker.Volume = 100;
speaker.Rate = 1;
speaker.Speak(text);
}
}
}
四、启动项目,生成一个exe。使用的时候需要传入两个参数,一个是生成wav文件的文件名,一个是要进行合成的文本。