C# 语音功能的实现方法
首先要安装speechsdk5.1 开发包和speechsdk5.1 langague pack(中英文) 语言包,不过vs2010里是自带speechsdk5.0的com组件的,也可以用。
简单讲一下四个方法:
朗读时,使用
voice.speak(string,speechvoicespeakflags.svsflagsasync);
暂停,使用
voice.pause();
从暂停中继续刚才的朗读,使用
voice.resume();
停止功能
voice.speak(string.empty, speechvoicespeakflags.svsfpurgebeforespeak);
这样就可以完整地实现了“朗读”、“暂停”、“继续”、“停止”的功能。
下面就直接给出实例代码:
private void button1_click(object sender, eventargs e)
{
analyse(this.textbox1.text);
}
public void analyse(string strspeak)
{
int icbeg = 0;
int iebeg = 0;
bool ischina = true;
for (int i = 0; i < strspeak.length; i++)
{
char chr = strspeak[i];
if (ischina)
{
if (convert.toint32(chr) <= 122 && convert.toint32(chr) >= 65)
{
int ilen = i - icbeg;
string strvalue =
strspeak.substring(icbeg, ilen);
speakchina(strvalue);
iebeg = i;
ischina = false;
}
}
else
{
if (convert.toint32(chr) > 122 || convert.toint32(chr) < 65)
{
int ilen = i - iebeg;
string strvalue =
strspeak.substring(iebeg, ilen);
this.speakenglishi(strvalue);
icbeg = i;
ischina = true;
}
}
}
if (ischina)
{ int ilen = strspeak.length - icbeg;
string strvalue = strspeak.substring(icbeg, ilen);
speakchina(strvalue);
}
else
{
int ilen = strspeak.length - iebeg;
string strvalue = strspeak.substring(iebeg, ilen);
speakenglishi(strvalue);
}
}
//中文
private void speakchina(string speak)
{
voice = new spvoice();
voice.voice = voice.getvoices(string.empty, string.empty).item(3);//其中3为中文,024为英文
voice.speak(speak, speechvoicespeakflags.svsfdefault);
}
//英文
private void speakenglishi(string speak)
{
voice = new spvoice();
voice.voice = voice.getvoices(string.empty, string.empty).item(0);//其中3为中文,024为英文
voice.speak(speak, speechvoicespeakflags.svsfdefault);
}
//保存语音
private void button2_click(object sender, eventargs e)
{
try
{
speechvoicespeakflags spflags = speechvoicespeakflags.svsflagsasync;
spvoice voice = new spvoice();
savefiledialog sfd = new savefiledialog();
sfd.filter = "all files (*.*)|*.*|wav files (*.wav)|*.wav";
sfd.title = "save to a wave file";
sfd.filterindex = 2;
sfd.restoredirectory = true;
if (sfd.showdialog() == dialogresult.ok)
{
speechstreamfilemode spfilemode = speechstreamfilemode.ssfmcreateforwrite;
spfilestream spfilestream = new spfilestream();
spfilestream.open(sfd.filename, spfilemode, false);
voice.audiooutputstream = spfilestream;
voice.speak(this.textbox1.text, spflags);
voice.waituntildone(100);
spfilestream.close();
}
}
catch (exception er)
{
messagebox.show("an error occured!", "speechapp", messageboxbuttons.ok, messageboxicon.error);
}
}