c#语音

时间:2024-11-22 22:04:20

1.新建WinForm程序,项目名称命名为Speech.

2.在COM组件中添加SpeechLib的引用。

c#语音

using SpeechLib;//添加语音引用

添加一个文本框并将其重命名为txtContent和两个按钮控件分别用做发音(btnRead)和保存(btnSave),实现代码如下:

private void btnRead_Click(object sender, EventArgs e)

{

Speak(txtContent.Text);

}

private void Speak(string speak)

{

//char[] chars=speak.ToArray();

SpVoice voice = new SpVoice();

voice.Rate = -2;//朗读速度

voice.Voice = voice.GetVoices(string.Empty,string.Empty).Item(0);

//for (int i = 0; i < chars.Length; i++)

//{

//    voice.Speak(chars[i].ToString(), SpeechVoiceSpeakFlags.SVSFDefault);

//}

voice.Speak(speak, SpeechVoiceSpeakFlags.SVSFDefault);

voice.Speak("完毕", SpeechVoiceSpeakFlags.SVSFDefault);

}

//保存语音

private void btnSave_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.txtContent.Text, SpFlags);

Voice.WaitUntilDone(100);

SpFileStream.Close();

}

}

catch (Exception)

{

MessageBox.Show("An Error Occured!", "SpeechApp", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

}

其中代码:

voice.Voice = voice.GetVoices(string.Empty,string.Empty).Item(0);

中0可以读取汉语和英语,而1只能读取英语,其他数字就报错,在网上也没找到合适答案,以后会继续修复现有问题。欢迎大神提出解决问题的办法