中英文语音合成与中文语音识别技术在c#中的应用(一)
2024-07-21 02:24:47
供稿:网友
在.net中,对英文语音有较好的支持,但是对中文语音的支持还没有加入进来,我们要想实现中文发音或中文语音识别,必需先安装微软的speech application sdk(sasdk),它的最新版本是 sapi 5.1 他能够识别中、日、英三种语言,你可以在这里下载:http://www.microsoft.com/speech/download/sdk51/,需要安装这两个文件speech sdk 5.1和5.1 language pack,其中5.1 language pack可以选择安装支持的语言。
安装好以后,我们就可以开始进行语音程序的开发了,当然,在这之前我们需要把sapi.dll通过如下图所示添加到引用中
下面我们设计一个能够朗读中英文混合语言的类:
我们将用单例模式实现该类,类的代码如下,我们将详细解释:
public class speach
{
private static speach _instance = null ;
private speechlib.spvoiceclass voice =null;
private speach()
{
buildspeach() ;
}
public static speach instance()
{
if (_instance == null)
_instance = new speach() ;
return _instance ;
}
private void setchinavoice()
{
voice.voice = voice.getvoices(string.empty,string.empty).item(0) ;
}
private void setenglishvoice()
{
voice.voice = voice.getvoices(string.empty,string.empty).item(1) ;
}
private void speakchina(string strspeak)
{
setchinavoice() ;
speak(strspeak) ;
}
private void speakenglishi(string strspeak)
{
setenglishvoice() ;
speak(strspeak) ;
}
public void analysespeak(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 (chr<=122&&chr>=65)
{
int ilen = i - icbeg ;
string strvalue = strspeak.substring(icbeg,ilen) ;
speakchina(strvalue) ;
iebeg = i ;
ischina = false ;
}
}
else
{
if (chr>122||chr<65)
{
int ilen = i - iebeg ;
string strvalue = strspeak.substring(iebeg,ilen) ;
this.speakenglishi(strvalue) ;
icbeg = i ;
ischina = true ;
}
}
}//end for
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 buildspeach()
{
if (voice == null)
voice = new spvoiceclass() ;
}
public int volume
{
get
{
return voice.volume ;
}
set
{
voice.setvolume((ushort)(value)) ;
}
}
public int rate
{
get
{
return voice.rate ;
}
set
{
voice.setrate(value) ;
}
}
private void speak(string strspeack)
{
try
{
voice.speak(strspeack,speechvoicespeakflags.svsflagsasync) ;
}
catch(exception err)
{
throw(new exception("发生一个错误:"+err.message)) ;
}
}
public void stop()
{
voice.speak(string.empty,speechlib.speechvoicespeakflags.svsfpurgebeforespeak) ;
}
public void pause()
{
voice.pause() ;
}
public void continue()
{
voice.resume() ;
}
}//end class
在 private speechlib.spvoiceclass voice =null;这里,我们定义个一个用来发音的类,并且在第一次调用该类时,对它用buildspeach方法进行了初始化。
我们还定义了两个属性volume和rate,能够设置音量和语速。
我们知道,spvoiceclass 有一个speak方法,我们发音主要就是给他传递一个字符串,它负责读出该字符串,如下所示。
private void speak(string strspeack)
{
try
{
voice.speak(strspeack,speechvoicespeakflags.svsflagsasync) ;
}
catch(exception err)
{
throw(new exception("发生一个错误:"+err.message)) ;
}
}
其中speechvoicespeakflags.svsflagsasync表示异步发音。
中国最大的web开发资源网站及技术社区,