先在引用里添加 System.Speech。
添加using语句
using System.Speech.Synthesis;
然后就是主程序了。
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SpeechSynthesizer speech = new SpeechSynthesizer();
speech.Rate = 1;//设置语速
speech.Volume = 100;//设置音量
获取本机上所安装的所有的Voice的名称
//string voicestring = "";
//foreach (InstalledVoice iv in speech.GetInstalledVoices())
//{
// voicestring += iv.VoiceInfo.Name + ",";
//}
//MessageBox.Show(voicestring);
speech.SelectVoice("Microsoft Huihui Desktop");//设置播音员(中文)
//speech.SpeakAsync("蒙多说你是个大娘们!");//异步播放
speech.SpeakCompleted += speech_SpeakCompleted;//绑定事件
}
void speech_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
{
MessageBox.Show("播放完成");
}
}
播音员在不同的电脑上可能会预装不同的播音员,如果播音员字符串错误,会出现如下异常:
System.ArgumentException:“不能设置语音。未安装匹配的语音,或语音被禁用。”
这时候就可以检索PC上安装的语音包来设置对应的语音了。