摘要:语音识别2种方法这里介绍第一种使用windows 7自带的SAPI,.netframework 必须在3.5以上<br/>using System.Speech.Synthesis;<br/>using System.Speech.Recognition;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Speech.Synthesis;
using System.Speech.Recognition;
namespace spspsps
{
public partial class sound : Form
{
SpeechSynthesizer synth = new SpeechSynthesizer();
public sound()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.textBox1.Text = "test speech";
}
private void button1_Click(object sender, EventArgs e)
{
this.button1.Enabled = false;
//获取本机上所安装的所有的Voice的名称
string voicestring = "";
foreach (InstalledVoice iv in synth.GetInstalledVoices())
{
voicestring += iv.VoiceInfo.Name + ",";
}
//调节音量和语速
synth.Volume = 100;
synth.Rate = 1;
//根据Voice的name属性确定要使用的Voice
// synth.SelectVoice("Microsoft Anna");
synth.SelectVoice("Microsoft Simplified Chinese");
//根据文字内容合成语音
synth.Speak(textBox1.Text);
this.button1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
if (button2.Text == "语音识别")
{
textBox1.Text = "";
button2.Text = "识别停止";
//创建语音识别类
SpRecognition x = new SpRecognition();
x.BeginRec(textBox1);
}
else
{
button2.Text = "语音识别";
//创建语音识别类
SpRecognition x = new SpRecognition();
x.EndRec();
}
}
public class SpRecognition
{
//private static SpRecognition _Instance = null;
private SpeechLib.ISpeechRecoGrammar isrg;
private SpeechLib.SpSharedRecoContextClass ssrContex = null;
//定义显示控件
private System.Windows.Forms.Control textBox1;
public SpRecognition()
{
ssrContex = new SpSharedRecoContextClass();
isrg = ssrContex.CreateGrammar(1);
//创建监视事件recHandle并随时将结果给ContexRecognition
SpeechLib._ISpeechRecoContextEvents_RecognitionEventHandler recHandle =
new _ISpeechRecoContextEvents_RecognitionEventHandler(ContexRecognition);
ssrContex.Recognition += recHandle;
}
//显示识别结果到show物件上
private void ContexRecognition(int iIndex, object obj, SpeechLib.SpeechRecognitionType type, SpeechLib.ISpeechRecoResult result)
{
textBox1.Text += "You Say:" + result.PhraseInfo.GetText(0, -1, true) + "\r\n";
}
//将识别结果丢给物件textbox1
public void BeginRec(Control tbResult)
{
isrg.DictationSetState(SpeechRuleState.SGDSActive);
textBox1 = tbResult;
}
public void EndRec()
{
isrg.DictationSetState(SpeechRuleState.SGDSActive);
}
}
}
}