似乎不可能实现。我甚至通过获取DtmfRecognitionEngine的私有_engine并调用其SetInputToWaveFile进行尝试,但没有成功。显然,将音调传输到DtmfRecognitionEngine的唯一方法是调用AddTone()。 我已经包含了一个样例语法文件和一些源代码供您参考。有趣的是,如果您取消注释dre.AddTone(),您会发现sre的事件和dre的事件都被触发了。
将调用切换到sre.RecognizeAsync()也无济于事。
看起来您需要使用不同的库...
PinGrammar.xml
<?xml version="1.0"?>
<grammar mode="dtmf" version="1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/2001/06/grammar
http://www.w3.org/TR/speech-grammar/grammar.xsd"
xmlns="http://www.w3.org/2001/06/grammar"
root="pin">
<rule id="digit">
<one-of>
<item> 0 </item>
<item> 1 </item>
<item> 2 </item>
<item> 3 </item>
<item> 4 </item>
<item> 5 </item>
<item> 6 </item>
<item> 7 </item>
<item> 8 </item>
<item> 9 </item>
</one-of>
</rule>
<rule id="pin" scope="public">
<one-of>
<item>
<item repeat="4">
<ruleref uri="#digit"/>
</item>
#
</item>
<item>
* 9
</item>
</one-of>
</rule>
</grammar>
来源:
using Microsoft.Speech.Recognition;
using System.Reflection;
namespace DTMF_Recognition
{
class Program
{
static void Main(string[] args)
{
Grammar grammar = null;
grammar = new Grammar("PinGrammar.xml");
DtmfRecognitionEngine dre = new DtmfRecognitionEngine();
dre.DtmfRecognized += dre_DtmfRecognized;
FieldInfo field = typeof(DtmfRecognitionEngine).GetField("_engine", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
var wrapper = field.GetValue(dre);
FieldInfo engineField = wrapper.GetType().GetField("_engine", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
SpeechRecognitionEngine sre = (SpeechRecognitionEngine)engineField.GetValue(wrapper);
dre.DtmfHypothesized += dre_DtmfHypothesized;
dre.DtmfRecognitionRejected += dre_DtmfRecognitionRejected;
dre.RecognizeCompleted += dre_RecognizeCompleted;
dre.LoadGrammar(grammar);
sre.SetInputToWaveFile(@"C:\Users\Clay Ver Valen\Desktop\3.wav");
sre.SpeechHypothesized += sre_SpeechHypothesized;
sre.SpeechDetected += sre_SpeechDetected;
sre.SpeechRecognitionRejected += sre_SpeechRecognitionRejected;
dre.RecognizeAsync();
System.Threading.Thread.Sleep(30000);
}
static void sre_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
{
int i = 1;
}
static void sre_SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
{
int i = 1;
}
static void sre_SpeechDetected(object sender, SpeechDetectedEventArgs e)
{
int i = 1;
}
static void dre_DtmfRecognitionRejected(object sender, DtmfRecognitionRejectedEventArgs e)
{
int i = 1;
}
static void dre_DtmfHypothesized(object sender, DtmfHypothesizedEventArgs e)
{
int i = 1;
}
static void dre_RecognizeCompleted(object sender, DtmfRecognizeCompletedEventArgs e)
{
int i = 1;
}
static void dre_DtmfRecognized(object sender, DtmfRecognizedEventArgs e)
{
int i = 1;
}
}
}