使用MSDN的SAPI,你如何取消同步语音识别操作,或者至少立即停止它?
将输入设置为null
会返回错误,表示在识别器识别时我无法执行此操作,并且无法使用异步识别。
以下是一个示例
class MainClass {
static void Main( ) {
SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();
recognizer.LoadGrammar(new DictationGrammar() );
recognizer.SetInputToDefaultAudioDevice();
recognizer.Recognize();
}
void MethodCalledFromOtherThread() {
//Since SpeechRecognitionEngine.Recognize() stops the current thread,
//this method is called from a different thread.
//I NEED the current thread to stop.
//Here I want to Cancel recognizer.Recognize
}
}
答案 0 :(得分:3)
这个MSDN article显示了如何在没有线程的情况下异步使用SAPI,并且可以随时取消操作。
这是一个如何尽早终止识别的非常简单的例子。
class Program
{
private static bool _userRequestedAbort = false;
// Indicate whether asynchronous recognition is complete.
static void Main(string[] args)
{
// Create an in-process speech recognizer.
using (SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine(new CultureInfo("en-US")))
{
// Create a grammar for choosing cities for a flight.
Choices cities = new Choices(new string[] { "Los Angeles", "New York", "Chicago", "San Francisco", "Miami", "Dallas" });
GrammarBuilder gb = new GrammarBuilder();
gb.Append("I want to fly from");
gb.Append(cities);
gb.Append("to");
gb.Append(cities);
// Construct a Grammar object and load it to the recognizer.
Grammar cityChooser = new Grammar(gb);
cityChooser.Name = ("City Chooser");
recognizer.LoadGrammarAsync(cityChooser);
bool completed = false;
// Attach event handlers.
recognizer.RecognizeCompleted += (o, e) =>
{
if (e.Error != null)
{
Console.WriteLine( "Error occurred during recognition: {0}", e.Error);
}
else if (e.InitialSilenceTimeout)
{
Console.WriteLine("Detected silence");
}
else if (e.BabbleTimeout)
{
Console.WriteLine("Detected babbling");
}
else if (e.InputStreamEnded)
{
Console.WriteLine("Input stream ended early");
}
else if (e.Result != null)
{
Console.WriteLine("Grammar = {0}; Text = {1}; Confidence = {2}", e.Result.Grammar.Name, e.Result.Text, e.Result.Confidence);
}
else
{
Console.WriteLine("No result");
}
completed = true;
};
// Assign input to the recognizer and start an asynchronous
// recognition operation.
recognizer.SetInputToDefaultAudioDevice();
Console.WriteLine("Starting asynchronous recognition...");
recognizer.RecognizeAsync();
// Wait for the operation to complete.
while (!completed)
{
if (_userRequestedAbort)
{
recognizer.RecognizeAsyncCancel();
break;
}
Thread.Sleep(333);
}
Console.WriteLine("Done.");
}
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}