在一些应用场合,需要播放语音,起到引导或警示的作用,之前方案一直是使用固定的音频文件,代码直接调用播放,这样虽然简便,但是也存在一些问题,比如,播放内容单一,变更时需要重新录制,语速音量不易调节等。后来发现在windows操作系统中,提供了文本到语音转换(TTS)工具,通过这个工具,可以直接将文本文字转化为语音播放,并且支持多种语言,在此基础上,c#又进一步包装,制作了SpeechSynthesizer类,位于System.Speech.Synthesis命名空间,可以方便的实现文本文字转换为语音播放。
SpeechSynthesizer类的官方应用示例代码如下。
using (SpeechSynthesizer synth = new SpeechSynthesizer())
{
// Configure the audio output.
synth.SetOutputToDefaultAudioDevice();
// Create a prompt from a string.
Prompt color = new Prompt("What is your favorite color?");
// Speak the contents of the prompt synchronously.
synth.Speak(color);
}
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
(来源于微软官方帮助文档)
在正式编写代码之前,需要先确认计算机软件环境
操作系统Windows10或更高版本(Windows7也可运行,但是生产的语音不够流程,有明显的机械感)
.NET Framework 4.6.1或更高版本
Visual Studio 2017或更高版本
按照以下步骤,在C#中创建winform应用程序。
- 打开Visual Studio并创建一个新的应用程序项目。
- 绘制窗体,窗体中主要包含一个TextBox,用于输入待转换的文本,两个TrackBar,用于控制语速和音量,一个Button,用于启动转化并播放语音。
- 引入需要的命名空间
using System.Speech.Synthesis;
- 定义变量,创建SpeechSynthesizer对象
SpeechSynthesizer synth = new SpeechSynthesizer();
- 初始化参数
public Form1()
{
InitializeComponent();
synth.SetOutputToDefaultAudioDevice();
synth.SpeakCompleted += new EventHandler
(SpeakCompled); }
- 播放语音
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
trackBar1.Enabled = false;
trackBar2.Enabled = false;
Prompt des = new Prompt(textBox1.Text);
synth.Rate = trackBar1.Value;
synth.Volume = trackBar2.Value;
synth.SpeakAsync(des);
}
- 语音播放完成后,响应事件
private void SpeakCompled(object sender, SpeakCompletedEventArgs e)
{
button1.Enabled = true;
trackBar1.Enabled = true;
trackBar2.Enabled = true;
}
- 完整实现代码如下