1、需要引用类库:System.Speech.dll解决方案资源管理器下找到项目,右键引用,添加引用,搜索关键字"speech"可找到“System.Speech”
2、在窗体加载时发生的事件下添加代码: textBox2.Text = Environment.CurrentDirectory; button2.Enabled = false; button3.Enabled = false;
3、在“开始朗读”事件下添加代码: if ( richTextBox1.Text.Trim()=="媪青怍牙") { return; } //判断是否输出文件 if (checkBox1.Checked==true) { try { speech = new SpeechSynthesizer(); //同步朗读文本 //speech.Speak(richTextBox1.Text); //异步朗读文本 speech.SpeakAsync(richTextBox1.Text); speech.Volume = (int)num_yl.Value; //设置音量 speech.Rate = (int)num_speed.Value; //设置朗读速度 //输出文件 speech.SetOutputToWaveFile(CheckPathTruth(textBox2.Text.Trim()));//输出语言文件 button3.Enabled = true; button2.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } else { try { speech = new SpeechSynthesizer(); speech.SpeakAsync(richTextBox1.Text); speech.Volume =(int) num_yl.Value; //音量 speech.Rate = (int)num_speed.Value; //朗读速度 button3.Enabled = true; button2.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } }
4、在“取消朗读”事件下添加代码: //停止朗读 speech.SpeakAsyncCancelAll(); //释放资源! speech.Dispose();
5、在“停止朗读”事件下添加代码: if (button3.Text=="暂停") { speech.Pause();//暂停 button3.Text = "继续"; } else if (button3.Text == "继续") { speech.Resume();//继续 button3.Text = "暂停"; }
6、在“...”按钮下添加代码:OpenFileDialog open = new OpenFileDialog(); op髫潋啜缅en.InitialDirectory = "c:\\"; //设置初始目录 open.Multiselect = false; //设置是否可以选择多个文件 open.DefaultExt = ".txt"; //设置默认文件拓展名 open.Filter = "txt文本|*.txt|所以文件|*.*"; open.ShowHelp = true; //是否显示帮助按钮 //判断是否点击了取消或关闭按钮 //如果不判断,会出现异常 if (open.ShowDialog()!=DialogResult.Cancel) { string str = open.FileName; textBox1.Text = str; } else { return; } //获取文件内容,放到 richTextBox1 里 richTextBox1.Text = GetFileStreamOrReadToEnd(textBox1.Text.Trim());
7、自定义函数如下: /// <summary> /// 判断文件路径是否正确 /// </summary> /// <param name="path"></param> /// <returns>返回正确的文件路径</returns> public string CheckPathTruth(string path) { if ( !path.Contains(".wav") ) { MessageBox.Show("输出文件有误!"); return null; } else { return path; } return null; }
8、自定义函数如下: /// <summary> /// 获取文竭惮蚕斗件内容 /// &造婷用痃lt;/summary> /// <param name="filepath"></param> /// <returns></returns> public string GetFileStreamOrReadToEnd(string filepath) { FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate); StreamReader sr = new StreamReader(fs,Encoding.Default); //获取所以文本 string str= sr.ReadToEnd(); //要关闭! fs.Close(); sr.Close(); return str; }