Luk*_*ood 0 c# text speech-recognition contains
我正在使用Microsoft的引擎在C#中编写自己的语音识别程序,并且我使程序识别命令的方式是读取文本文件中已有的内容.这个问题是,我必须完全按照它所写的命令说明.例如,如果命令是"什么是明天日期",我不能说"明天是什么日期".我想办法解决它,那就是使用Contains方法.这是我的代码,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.IO;
namespace TestDECA
{
public partial class Form1 : Form
{
SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();
SpeechSynthesizer DECA = new SpeechSynthesizer();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_recognizer.SetInputToDefaultAudioDevice();
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(File.ReadAllLines(@"D:\Luke's Documents\Speech Commands\TestCommands.txt")))));
_recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(_recongizer_SpeechRecognized);
_recognizer.RecognizeAsync(RecognizeMode.Multiple);
}
void _recongizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string speech = e.Result.Text;
if (speech.Contains("open" && "fire fox"))
{
System.Diagnostics.Process.Start(@"D:\Program Files (x86)\Mozilla Firefox\firefox.exe");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我想检查语音是否包含"open"和"fire fox"字样.但是,Visual Studio给出了一个错误,指出&&运算符不能应用于字符串.有没有办法检查文本是否包含这些单词?任何帮助都将不胜感激.
该String.Contains()方法需要一个string. "open" && "fire fox"不评估为string.如果要检查字符串是否包含两个不同的值,请执行以下操作:
if (speech.Contains("open") && speech.Contains("fire fox"))
{
...
}
Run Code Online (Sandbox Code Playgroud)
您可以创建一个扩展方法来帮助简化:
public static bool ContainsAll(this string str, params string[] values)
{
foreach (var value in values)
{
if (!str.Contains(value)) return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
if (speech.ContainsAll("open", "fire fox"))
{
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |