我是C#的新手,我不确定是否在这个问题的正确论坛上写作。我正在尝试实现文本程序语音。 (winforms) 我将Windows.cs.xml代码移至我的程序(Form1.cs),但遇到此错误
“名称AudioLevelUpdated在当前上下文中不存在”
。 我尝试添加Assembly(System.Speech)并使用指令,但没有任何改进。请帮助
这是代码
SpeechRecognitionEngine speechRecognitionEngine = null;
/// <summary>
/// list of predefined commands
/// </summary>
List<Word> words = new List<Word>();
#endregion
#region ctor
/// <summary>
/// Initializes a new instance of the <see cref="Form1"/> class.
/// </summary>
//public event EventHandler<AudioLevelUpdatedEventArgs> AudioLevelUpdated;
public Form1()
{
InitializeComponent();
try
{
// create the engine
speechRecognitionEngine = createSpeechEngine("de-DE");
// hook to events
speechRecognitionEngine.AudioLevelUpdated += new EventHandler<AudioLevelUpdatedEventArgs>(engine_AudioLevelUpdated);
speechRecognitionEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(engine_SpeechRecognized);
// load dictionary
loadGrammarAndCommands();
// use the system's default microphone
speechRecognitionEngine.SetInputToDefaultAudioDevice();
// start listening
speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Voice recognition failed");
}
}
答案 0 :(得分:1)
通过查看您的代码,我看到这两行:
speechRecognitionEngine.AudioLevelUpdated += new EventHandler<AudioLevelUpdatedEventArgs>(engine_AudioLevelUpdated);
speechRecognitionEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(engine_SpeechRecognized);
我不确定它们是正确的。至少我以前从未见过事件处理程序以这种格式订阅。编辑:只是尝试以这种方式订阅事件,它的工作原理。似乎太冗长了!
通常它们看起来像:
speechRecognitionEngine.AudioLevelUpdated += engine_AudioLevelUpdated;
speechRecognitionEngine.SpeechRecognized += engine_SpeechRecognized;
然后您将拥有处理程序方法:
private void engine_AudioLevelUpdated(object sender, AudioLevelUpdatedEventArgs e)
{
// Your code when the event fires.
}
private void engine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
// Your code when the event fires.
}
在您的代码中没有看到您已实现这些方法的地方。那可能是您的错误所在吗?
我已经将System.Speech添加到测试应用程序中,并实例化了SpeechRecognitionEngine并订阅了这两个事件,并且该应用程序启动时没有错误。