C# 语音功能的实现方法
时间:2023-03-15 13:40:51
首先要安装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);
}
}