C#如何实现文字转语音功能
导读:本文共3508字符,通常情况下阅读需要12分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 效果图关键是,c#有现成的一个引用右键点击项目 > 添加引用 > .Net > 找到System.Speech点击确定控制台程序代码:usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Speech.Synthes... ...
音频解说
目录
(为您整理了一些要点),点击可以直达。效果图
关键是,c#有现成的一个引用
右键点击项目 > 添加引用 > .Net > 找到System.Speech点击确定
控制台程序代码:
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Speech.Synthesis;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespaceTxtToVoice{classProgram{[STAThread]//默认线程模型是单线程单元(STA)模式staticvoidMain(string[]args){//Application.EnableVisualStyles();//Application.SetCompatibleTextRenderingDefault(false);//Application.Run(newForm1());//return;OpenFileDialogopen=newOpenFileDialog();open.Title="请选择文本";//打开的文件选择对话框上的标题open.Filter="文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";//设置文件类型open.InitialDirectory=@"D:\project\";//默认打开目录open.FilterIndex=1;//设置默认文件类型显示顺序open.RestoreDirectory=false;//是否记忆上次打开的目录//open.Multiselect=true;//是否允许多选stringcontent=string.Empty;if(open.ShowDialog()==DialogResult.OK)//按下确定选择的按钮{string[]filename=open.FileNames;//获取多个文件的路径及文件名并存入数组MessageBox.Show(filename[0]);//MessageBox.Show(filename[1]);//MessageBox.Show(open.FileName);//获取路径及文件名//MessageBox.Show(open.SafeFileName);//获取文件名content=ReadFile(filename[0]);}//-----------------------------------读出文件内容---------------------------------SpeechSynthesizervoice=newSpeechSynthesizer();//创建语音实例voice.Rate=-1;//设置语速,[-10,10]voice.Volume=100;//设置音量,[0,100]//voice.SpeakAsync("HellowWord");//播放指定的字符串,这是异步朗读//下面的代码为一些SpeechSynthesizer的属性,看实际情况是否需要使用voice.SpeakAsyncCancelAll();//取消朗读voice.Speak(content);//同步朗读voice.Pause();//暂停朗读voice.Resume();//继续朗读voice.Dispose();//释放所有语音资源}///<summary>///读取文件,返回相应字符串///</summary>///<paramname="fileName">文件路径</param>///<returns>返回文件内容</returns>privatestaticstringReadFile(stringfileName){StringBuilderstr=newStringBuilder();using(FileStreamfs=File.OpenRead(fileName)){longleft=fs.Length;intmaxLength=100;//每次读取的最大长度intstart=0;//起始位置intnum=0;//已读取长度while(left>0){byte[]buffer=newbyte[maxLength];//缓存读取结果char[]cbuffer=newchar[maxLength];fs.Position=start;//读取开始的位置num=0;if(left<maxLength){num=fs.Read(buffer,0,Convert.ToInt32(left));}else{num=fs.Read(buffer,0,maxLength);}if(num==0){break;}start+=num;left-=num;str=str.Append(Encoding.UTF8.GetString(buffer));}}returnstr.ToString();}}}
窗体代码:
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.IO;usingSystem.Linq;usingSystem.Speech.Synthesis;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespaceTxtToVoiceForm{publicpartialclassForm2:Form{privateSpeechSynthesizerspeech;///<summary>///音量///</summary>privateintvalue=100;///<summary>///语速///</summary>privateintrate;publicForm2(){InitializeComponent();ReadlocalFile();comboBox1.SelectedIndex=0;}privatevoidcomboBox1_SelectedIndexChanged(objectsender,EventArgse){rate=Int32.Parse(comboBox1.Text);}//privatevoid打开文件ToolStripMenuItem_Click(objectsender,EventArgse)//{//this.ReadlocalFile();//}///<summary>///读取本地文本文件的方法///</summary>privatevoidReadlocalFile(){varopen=newOpenFileDialog();open.ShowDialog();//得到文件路径stringpath=open.FileName;if(path.Trim().Length==0){return;}varos=newStreamReader(path,Encoding.UTF8);stringstr=os.ReadToEnd();textBox1.Text=str;}privatevoid清空内容ToolStripMenuItem_Click(objectsender,EventArgse){textBox1.Text="";}privatevoidbutton1_Click(objectsender,EventArgse){stringtext=textBox1.Text;if(text.Trim().Length==0){MessageBox.Show("不能阅读空内容!","错误提示");return;}if(button1.Text=="语音试听"){speech=newSpeechSynthesizer();newThread(Speak).Start();button1.Text="停止试听";}elseif(button1.Text=="停止试听"){speech.SpeakAsyncCancelAll();//停止阅读button1.Text="语音试听";}}privatevoidSpeak(){speech.Rate=rate;//speech.SelectVoice("MicrosoftLili");//设置播音员(中文)//speech.SelectVoice("MicrosoftAnna");//英文speech.Volume=value;speech.SpeakAsync(textBox1.Text);//语音阅读方法speech.SpeakCompleted+=speech_SpeakCompleted;//绑定事件}///<summary>///语音阅读完成触发此事件///</summary>///<paramname="sender"></param>///<paramname="e"></param>voidspeech_SpeakCompleted(objectsender,SpeakCompletedEventArgse){button1.Text="语音试听";}///<summary>///拖动进度条事件///</summary>///<paramname="sender"></param>///<paramname="e"></param>privatevoidtrackBar1_Scroll(objectsender,EventArgse){//因为trackBar1的值为(0-10)之间而音量值为(0-100)所以要乘10;value=trackBar1.Value*10;}privatevoidbutton2_Click(objectsender,EventArgse){stringtext=textBox1.Text;if(text.Trim().Length==0){MessageBox.Show("空内容无法生成!","错误提示");return;}this.SaveFile(text);}///<summary>///生成语音文件的方法///</summary>///<paramname="text"></param>privatevoidSaveFile(stringtext){speech=newSpeechSynthesizer();vardialog=newSaveFileDialog();dialog.Filter="*.wav|*.wav|*.mp3|*.mp3";dialog.ShowDialog();stringpath=dialog.FileName;if(path.Trim().Length==0){return;}speech.SetOutputToWaveFile(path);speech.Volume=value;speech.Rate=rate;speech.Speak(text);speech.SetOutputToNull();MessageBox.Show("生成成功!在"+path+"路径中!","提示");}privatevoidlabel1_Click(objectsender,EventArgse){}privatevoidlabel3_Click(objectsender,EventArgse){this.ReadlocalFile();}}}
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:
C#如何实现文字转语音功能的详细内容,希望对您有所帮助,信息来源于网络。