如何在语音识别程序中添加添加数组,请参见下面的代码?我试过了
使用streamRead读取一个字符串并创建一个数组并放在commands.Add(new String[]
之后,请参阅下面的代码,但无法实现。
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Globalization;
using System.IO;
//Speech to Text
amespace CSharp_Speech_ConsoleApp
{
class Program
{
[DllImport("winmm.dll")]
public static extern int waveInGetNumDevs();
SpeechRecognitionEngine recognizer = new
SpeechRecognitionEngine(new
System.Globalization.CultureInfo("en-US"));
static void Main(string[] args)
{
// Make a Keywords array
Choices commands = new Choices();
//How to make this array by importing strings from a file ?
commands.Add(new String[] { "Good morning.","Hello Mike.",
"Good morning Eddy.","Good afternoon.","Good Evening","Hello",
"How are you", "Listen to me Mike", "Stop listening Mike!"
});
GrammarBuilder gBuilder = new GrammarBuilder();
gBuilder.Append(commands);
Grammar grammar = new Grammar(gBuilder);
recogEngine.LoadGrammar(grammar);
//get total number of sound input devices
int waveInDevicesCount = waveInGetNumDevs();
if(waveInDevicesCount == 0)
{
Console.WriteLine("No microphone detected.!");
}
else
{
Console.WriteLine("Microphone detected. ");
recogEngine.SetInputToDefaultAudioDevice();
recogEngine.SpeechRecognized += recogEngine_SpeechRecognized;
recogEngine.RecognizeAsync(RecognizeMode.Multiple);
}
Console.ReadLine();
}
// Console Display Speech Recognized result Text
static void recogEngine_SpeechRecognized(object sender,
SpeechRecognizedEventArgs e)
{
string managedString = e.Result.Text;
char[] st = managedString.ToCharArray();
Console.WriteLine(st);
}
}
}
答案 0 :(得分:3)
如何通过从文件导入字符串来创建数组?
这将为您提供文件中的所有行:
var lines = File.ReadAllLines(@"PathToYourFile");
以上内容将文件中的所有行都读入内存。还有另一种方法可以在需要时逐个读取这些行:
var lines = File.ReadLines(@"PathToYourFile");
这个返回IEnumerable<string>
。例如,假设您的文件有1000行,ReadAllLines
将所有1000行读入内存。但ReadLines
会在需要时逐一读取它们。因此,如果您这样做:
var lines = File.ReadLines(@"PathToYourFile");
var line1 = lines.First();
var lastLine = lines.Last();
即使您的文件有1000行,它也只会将第一行和最后一行读入内存。
那么何时使用ReadLines
方法?
让我们说你需要读一个有1000行的文件,而你感兴趣的只有900到920行,那么你可以这样做:
var lines = File.ReadLines(@"PathToYourFile");
var line900To920 = lines.Skip(899).Take(21);