//2012-03-02 庞海峰
public class VoiceListItem
{
public InstalledVoice iVoice;
public override string ToString()
{
return iVoice.VoiceInfo.Culture.DisplayName;
}
}
class SpeechHelper
{
private SpeechSynthesizer synth;
public SpeechSynthesizer MySynth
{
get {
if (synth == null)
{
synth = new SpeechSynthesizer();
}
return synth;
}
set { synth = value; }
}
/// <summary>
/// 返回当前机器中的语言列表(中文名称+InstalledVoice对象实例)
/// </summary>
/// <returns>arrayList形式</returns>
public ArrayList GetVoicesList()
{
ArrayList al = new ArrayList();
foreach (InstalledVoice iv in MySynth.GetInstalledVoices())
{
VoiceListItem vli = new VoiceListItem();
vli.iVoice = iv;
if (!isExistInList(vli, al))
{
al.Add(vli);
}
}
return al;
}
/// <summary>
/// 是否在已有列表中存在
/// </summary>
/// <param name="vli"></param>
/// <param name="al"></param>
/// <returns></returns>
bool isExistInList(VoiceListItem vli,ArrayList al)
{
bool isExist = false;
foreach (VoiceListItem item in al)
{
if (item.iVoice.VoiceInfo.Culture.DisplayName == vli.iVoice.VoiceInfo.Culture.DisplayName)
{
isExist = true;
break;
}
}
return isExist;
}
/// <summary>
/// 根据语言列举朗读者
/// </summary>
/// <param name="language"></param>
/// <returns></returns>
public ArrayList GetVoiceInfoNameByLanguage(string language)
{
ArrayList al = new ArrayList();
foreach (InstalledVoice iv in MySynth.GetInstalledVoices())
{
if (iv.VoiceInfo.Culture.Name == language)
al.Add(iv.VoiceInfo.Name);
}
return al;
}
/// <summary>
/// 判断是否存在某种语言
/// </summary>
/// <param name="languageID">0:中文 1:日语 2:英语</param>
/// <returns></returns>
public bool IsExistLanguage(string language)
{
bool isExist = false;
foreach (InstalledVoice iv in MySynth.GetInstalledVoices())
{
if (iv.VoiceInfo.Culture.Name == language)
{
isExist = true;
break;
}
}
return isExist;
}
/// <summary>
/// 转换为英文标识
/// </summary>
/// <param name="languageID">0:中文 1:日语 2:英语</param>
/// <returns></returns>
public string ConvertToLanguageName(int languageID)
{
string language = "zh-CN";
switch (languageID)
{
case 0:
{
language = "zh-CN";
break;
}
case 1:
{
language = "ja-JP";
break;
}
case 2:
{
language = "en-US";
break;
}
}
return language;
}
/// <summary>
/// 设置语音引擎
/// </summary>
/// <param name="voiceName"></param>
/// <returns>是否切换成功</returns>
public bool SetVoice(string voiceName)
{
try
{
MySynth.SelectVoice(voiceName);
return true;
}
catch (Exception exp)
{
return false;
}
}
/// <summary>
/// 根据ID设置发音引擎
/// </summary>
/// <param name="languageID">0:中文 1:日语 2:英语</param>
public void SetVoiceByLanguageID(int languageID)
{
string language = ConvertToLanguageName(languageID);
System.Globalization.CultureInfo cif = new System.Globalization.CultureInfo(language);
if (IsExistLanguage(language))
{
MySynth.SelectVoiceByHints(VoiceGender.NotSet, VoiceAge.NotSet, 1, cif);
}
}
}