简体   繁体   中英

System.Speech Voice Recognition not working

I am using c# system.speech , and i have limited number of sentences that i wants to recognize. Here is code

  SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();
    String[] Sentences = File.ReadAllLines(samplePath);
    Choices sentences = new Choices();
    sentences.Add(Sentences);
    GrammarBuilder gBuilder = new GrammarBuilder(sentences);
    Grammar g = new Grammar(gBuilder);
    g.Enabled = true;
    recognizer.LoadGrammar(g);

    try
    {
        recognizer.SetInputToWaveFile(filePath);
        RecognitionResult result = recognizer.Recognize();
        String ret = result.Text;
        recognizer.Dispose();
        return ret;
    }
    catch (InvalidOperationException exception) { }
    return "";

This code throws exception when I give it some wav file and reason of exception is it can't find match in sample sentences. Can I force it so it must select on sentence?

You are getting NullReferenceException because the format of your .wav file's format is different than how System.Speech.Recognition.SpeechRecognitionEngine is trying to analyse .wav files by default when using the SetInputToWaveFile method.

In order to change the read format you should use the SetInputToAudioStream method instead:

using (FileStream stream = new FileStream("C:\\3.wav", FileMode.Open))
{
    recognizer.SetInputToAudioStream(stream, new SpeechAudioFormatInfo(5000, AudioBitsPerSample.Sixteen, AudioChannel.Stereo));
    RecognitionResult result = recognizer.Recognize();
    string ret = result.Text;
}

This way it reads your .wav file as a stereo file , at 16bps and with 5000 samples per second as your .wav file is really encoded.

Note: this solved the problem for me ON YOUR FILE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM