需要下载安装Microsoft Speech SDK 5.1和Microsoft Speech SDK 5.1 Language Pack,引用Interop.SpeechLib.dll。
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DotNetSpeech;
namespace ReadFiles
{
public partial class sound : Form
{
public SpVoice Voice = new SpVoice();
Speach sp;
public sound()
{
InitializeComponent();
}
private void sound_Load(object sender, EventArgs e)
{
string strVoice;
foreach (SpeechLib.ISpeechObjectToken sot in Voice.GetVoices("", ""))
{
strVoice = sot.GetDescription(0);
this.cboVoxOptions.Items.Add(strVoice);
}
if (cboVoxOptions.Items.Count <= 0)
{
MessageBox.Show(this, "This system does not " + "contain Text-to-Speech capability.");
}
this.cboVoxOptions.SelectedIndex = 0;
}
/// <summary>
/// 朗读
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSynthesis_Click(object sender, EventArgs e)
{
loadSound();
}
/// <summary>
/// 朗读内容方法
/// </summary>
public void loadSound()
{
try
{
#region 测试代码
//SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
//Voice.WaitUntilDone(1000); //阻塞进程,直到声音播放完毕或者超时
//ArrayList al = new ArrayList();
//al = getAllRole();
//for (int i = 0; i < al.Count; i++)
//{
// listBox1.Items.Add(i);
//}
//Voice.Speak(this.txtSpeakText.Text, SpFlags);
#endregion
sp = new Speach(cboVoxOptions.SelectedIndex);
sp.setRate(tbRate.Value);
sp.setVolume(tbSound.Value);
sp.AnalyseSpeak(this.txtSpeakText.Text);
}
catch (Exception er)
{
MessageBox.Show(er.ToString());
}
}
#region 发音设置
public class Speach
{
private static Speach _Instance = null;
private SpeechLib.SpVoiceClass voice = null;
private int _selectedindex;
public Speach()
{
BuildSpeach();
}
public Speach(int selectedindex)
{
_selectedindex = selectedindex;
BuildSpeach();
}
public static Speach instance()
{
if (_Instance == null)
_Instance = new Speach();
return _Instance;
}
/// <summary>
/// 设置为中文
/// </summary>
private void SetChinaVoice()
{
voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(0);
//voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(_selectedindex);
}
/// <summary>
/// 设置为英文
/// </summary>
private void SetEnglishVoice()
{
voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(1);
//voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(_selectedindex);
}
/// <summary>
/// 读中文
/// </summary>
/// <param name="strSpeak"></param>
private void SpeakChina(string strSpeak)
{
SetChinaVoice();
Speak(strSpeak);
}
/// <summary>
/// 读英文
/// </summary>
/// <param name="strSpeak"></param>
private void SpeakEnglishi(string strSpeak)
{
SetEnglishVoice();
Speak(strSpeak);
}
/// <summary>
/// 中英文读取方法
/// </summary>
/// <param name="strSpeak"></param>
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;
}
}
}
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 SpeechLib.SpVoiceClass();
}
}
#region 音量和语速设置 暂时没用
/// <summary>
/// 音量
/// </summary>
public int Volume
{
get
{
return voice.Volume;
}
set
{
voice.SetVolume((ushort)(value));
}
}
/// <summary>
/// 语速
/// </summary>
public int Rate
{
get
{
return voice.Rate;
}
set
{
voice.SetRate(value);
}
}
public Speach(int volume, int rate)
{
this.Volume = volume;
this.Rate = rate;
}
#endregion
private void Speak(string strSpeack)
{
try
{
//voice.Speak(strSpeack, SpeechVoiceSpeakFlags.SVSFlagsAsync);
voice.Speak(strSpeack, SpeechLib.SpeechVoiceSpeakFlags.SVSFlagsAsync);
}
catch (Exception err)
{
throw (new Exception("发生一个错误:" + err.Message));
}
}
/// <summary>
/// 开始
/// </summary>
public void Resume()
{
voice.Resume();
}
/// <summary>
/// 暂停
/// </summary>
public void Pause()
{
voice.Pause();
}
/// <summary>
/// 停止
/// </summary>
public void Stop()
{
voice.Speak("", SpeechLib.SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
}
/// <summary>
/// rate 设置语速
/// </summary>
/// <param name="rate">语速</param>
public void setRate(int rate)
{
voice.Rate = rate;
}
/// <summary>
/// 设置音量
/// </summary>
/// <param name="volume">音量</param>
public void setVolume(int volume)
{
voice.Volume = volume;
}
}
#endregion
#region ....
public class SpRecognition
{
private static SpRecognition _Instance = null;
private SpeechLib.ISpeechRecoGrammar isrg;
private SpeechLib.SpSharedRecoContextClass ssrContex = null;
private System.Windows.Forms.Control cDisplay;
private SpRecognition()
{
ssrContex = new SpeechLib.SpSharedRecoContextClass();
isrg = ssrContex.CreateGrammar(1);
//SpeechLib._ISpeechRecoContextEvents_RecognitionEventHandler recHandle = new _ISpeechRecoContextEvents_RecognitionEventHandler(ContexRecognition);
SpeechLib._ISpeechRecoContextEvents_RecognitionEventHandler recHandle = new SpeechLib._ISpeechRecoContextEvents_RecognitionEventHandler(ContexRecognition);
ssrContex.Recognition += recHandle;
}
public void BeginRec(Control tbResult)
{
//isrg.DictationSetState(SpeechRuleState.SGDSActive);
isrg.DictationSetState(SpeechLib.SpeechRuleState.SGDSActive);
cDisplay = tbResult;
}
public static SpRecognition instance()
{
if (_Instance == null)
{
_Instance = new SpRecognition();
}
return _Instance;
}
public void CloseRec()
{
//isrg.DictationSetState(SpeechRuleState.SGDSInactive);
isrg.DictationSetState(SpeechLib.SpeechRuleState.SGDSInactive);
}
private void ContexRecognition(int iIndex, object obj, SpeechLib.SpeechRecognitionType type, SpeechLib.ISpeechRecoResult result)
{
cDisplay.Text += result.PhraseInfo.GetText(0, -1, true);
}
}
#endregion
#region 暂时没用到
/// <summary>
/// 男女发音示例
/// </summary>
//public void SaySound()
//{
// SpeechVoiceSpeakFlags flag = SpeechVoiceSpeakFlags.SVSFlagsAsync;
// SpVoice voice = new SpVoice();
// voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(3);
// //Item(0)单词男声Sam
// //Item(1)单词男声Mike
// //Item(2)单词女声Mary
// //Item(3)中文发音,如果是英文,就依单词字母一个一个发音
// //voice.Speak(textBox1.Text, flag);
//}
/// <summary>
/// 返回当前系统的所有角色
/// </summary>
/// <returns></returns>
public ArrayList getAllRole()
{
ArrayList roleArr = new ArrayList();
for (int i = 0; i < Voice.GetVoices("", "").Count; i++)
{
roleArr.Add(Voice.GetVoices("", "").Item(i).GetDescription(0));
}
return roleArr;
}
/// <summary>
/// 获得当前的语速
/// </summary>
/// <returns></returns>
public int getRate()
{
int a;
a = Voice.Rate;
return (a);
}
/// <summary>
/// 获取当前声音大小
/// </summary>
/// <returns></returns>
public int getVolume()
{
int a;
a = Voice.Volume;
return (a);
}
#endregion
#region 导出语音
private void buttonTTStoWave_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(txtSpeakText.Text, SpFlags);
//Voice.WaitUntilDone(Timeout.Infinite);
Voice.WaitUntilDone(1000);
SpFileStream.Close();
}
}
catch (Exception er)
{
MessageBox.Show("An Error Occured!", "SpeechApp", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region 导出声音
private void ttsToWave()
{
SpeechLib.SpeechVoiceSpeakFlags SpFlags = SpeechLib.SpeechVoiceSpeakFlags.SVSFlagsAsync;
SpeechLib.SpVoice spvoice = new SpeechLib.SpVoice();
Speach sp = new Speach();
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)
{
SpeechLib.SpeechStreamFileMode SpFileMode = SpeechLib.SpeechStreamFileMode.SSFMCreateForWrite;
SpeechLib.SpFileStream SpFileStream = new SpeechLib.SpFileStream();
SpFileStream.Open(sfd.FileName, SpFileMode, false);
spvoice.AudioOutputStream = SpFileStream;
spvoice.Speak(txtSpeakText.Text, SpFlags);
spvoice.WaitUntilDone(1000);
SpFileStream.Close();
}
}
#endregion
#region 播放
private void btnPlay_Click(object sender, EventArgs e)
{
sp.Resume();
}
#endregion
#region 暂停
private void btnStop_Click(object sender, EventArgs e)
{
sp.Pause();
}
#endregion
private void btExport_Click(object sender, EventArgs e)
{
ttsToWave();
}
}
}