首先要安裝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);
}
}