none
인덱스가 범위를 벗어났습니다 해결좀 해주세요... RRS feed

  • 질문

  • JarvisDriver.cs

    #region using directives

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Speech.Recognition;
    using System.Speech.Synthesis;
    using System.Windows;
    using System.Diagnostics;

    #endregion


    namespace SpeechRecognition
    {
        class JarvisDriver
        {
            #region locals

            /// <summary>
            /// the engine
            /// </summary>
            SpeechRecognitionEngine speechRecognitionEngine = null;

            /// <summary>
            /// The speech synthesizer
            /// </summary>
            SpeechSynthesizer speechSynthesizer = null;

            /// <summary>
            /// list of predefined commands
            /// </summary>
            List<Word> words = new List<Word>();

            /// <summary>
            /// The last command
            /// </summary>
            string lastCommand = "";

            /// <summary>
            /// The name to call commands
            /// </summary>
            string aiName = "Jarvis";

            #endregion

            #region ctor

            public void Start()
            {

                try
                {
                    // create the engine
                    speechRecognitionEngine = createSpeechEngine("en-US");

                    // hook to event
                    speechRecognitionEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(engine_SpeechRecognized);

                    // load dictionary
                    loadGrammarAndCommands();

                    // use the system's default microphone
                    speechRecognitionEngine.SetInputToDefaultAudioDevice();

                    // start listening
                    speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);

                    //Create the speech synthesizer
                    speechSynthesizer = new SpeechSynthesizer();
                    speechSynthesizer.Rate = -5;
                   
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Voice recognition failed " + ex.Message);
                }

                //Keeps the command prompt going until you say jarvis quit
                while(lastCommand.ToLower() != "quit")
                {

                }

            }

            #endregion

            #region internal functions and methods

            /// <summary>
            /// Creates the speech engine.
            /// </summary>
            /// <param name="preferredCulture">The preferred culture.</param>
            /// <returns></returns>
            private SpeechRecognitionEngine createSpeechEngine(string preferredCulture)
            {
                foreach (RecognizerInfo config in SpeechRecognitionEngine.InstalledRecognizers())
                {
                    if (config.Culture.ToString() == preferredCulture)
                    {
                        speechRecognitionEngine = new SpeechRecognitionEngine(config);
                        break;
                    }
                }

                // if the desired culture is not found, then load default
                if (speechRecognitionEngine == null)
                {
                    Console.WriteLine("The desired culture is not installed on this machine, the speech-engine will continue using "
                        + SpeechRecognitionEngine.InstalledRecognizers()[0].Culture.ToString() + " as the default culture.",
                        "Culture " + preferredCulture + " not found!");
                    speechRecognitionEngine = new SpeechRecognitionEngine(SpeechRecognitionEngine.InstalledRecognizers()[0]);
                }

                return speechRecognitionEngine;
            }

            /// <summary>
            /// Loads the grammar and commands.
            /// </summary>
            private void loadGrammarAndCommands()
            {
                try
                {
                    Choices texts = new Choices();
                    texts.Add("Javis");
                    string[] lines = File.ReadAllLines(Environment.CurrentDirectory + "");
                    foreach (string line in lines)
                    {
                        // skip commentblocks and empty lines..
                        if (line.StartsWith("--") || line == String.Empty) continue;

                        // split the line
                        var parts = line.Split(new char[] { '|' });

                        // add commandItem to the list for later lookup or execution
                        words.Add(new Word() { Text = parts[0], AttachedText = parts[1], IsShellCommand = (parts[2] == "true") });

                        // add the text to the known choices of speechengine
                        texts.Add(parts[0]);
                    }
                    Grammar wordsList = new Grammar(new GrammarBuilder(texts));
                    speechRecognitionEngine.LoadGrammar(wordsList);

                    DictationGrammar dict = new DictationGrammar();
                    speechRecognitionEngine.LoadGrammar(dict);
                   
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            /// <summary>
            /// Gets the known command.
            /// </summary>
            /// <param name="command">The order.</param>
            /// <returns></returns>
            private string getKnownTextOrExecute(string command)
            {
                if (!command.StartsWith("Jarvis "))
                    return "";
                else
                    command = command.Replace("Jarvis ", "");

                Console.WriteLine(command);
                try
                {
                    var cmd = words.Where(c => c.Text == command).First();

                    if (cmd.IsShellCommand)
                    {
                        Process proc = new Process();
                        proc.EnableRaisingEvents = false;
                        proc.StartInfo.FileName = cmd.AttachedText;
                        proc.Start();
                        lastCommand = command;

                        if (command.ToLower() == "i have a burn victim")
                            return "Fetching list of burn centers for you sir";
                        else
                            return "I've started : " + command;
                    }
                    else
                    {
                        lastCommand = command;
                        return cmd.AttachedText;
                    }
                }
                catch (Exception)
                {
                    lastCommand = command;
                    return command;
                }

               
            }

            #endregion

            #region speechEngine events

            /// <summary>
            /// Handles the SpeechRecognized event of the engine control.
            /// </summary>
            /// <param name="sender">The source of the event.</param>
            /// <param name="e">The <see cref="System.Speech.Recognition.SpeechRecognizedEventArgs"/> instance containing the event data.</param>
            void engine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
            {
                string command = getKnownTextOrExecute(e.Result.Text);

                if (command != "")
                    speechSynthesizer.SpeakAsync(command);
            }

            #endregion

        }
    }

    Program.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace SpeechRecognition
    {
        class Program
        {
            static void Main(string[] args)
            {
                JarvisDriver jarvis = new JarvisDriver();
                jarvis.Start();
            }
        }
    }

    Word.cs

    namespace SpeechRecognition
    {
        /// <summary>
        /// represents a word
        /// </summary>
        public class Word
        {
            public Word() { }
            public string Text { get; set; }
            public string AttachedText { get; set; }
            public bool IsShellCommand { get; set; }
        }
    }

    example.txt

    -- format
    -- [text to recognize] | [text to display or execute] | [is text a command?]

    -- simple text --
    one|you said "one"|false
    two|you said "two"|false
    three|you said "three"|false
    four|you said "four"|false
    five|you said "five"|false
    six|you said "six"|false
    seven|you said "seven"|false
    eight|you said "eight"|false
    nine|you said "nine"|false
    ten|you said "ten"|false
    Patrick|you said "Patrick"|false
    do you like me|you made me I kinda have too|false


    -- commands --
    wordpad|wordpad.exe|true
    calculator|calc.exe|true

    이렇게 프로그래밍을 했는데

    인덱스 범위가 벗어났습니다.인덱스는 음수가 아니어야 하며 컬렉션의 크기보다 작아야 합니다.

    매개 변수 이름 : index 라고만 떠요

    2015년 7월 26일 일요일 오후 1:39

답변

  • 안녕하세요.

    가만보니까 여기서 나는것 같네요.

    참고하세요.

                    Console.WriteLine("The desired culture is not installed on this machine, the speech-engine will continue using "
                        + SpeechRecognitionEngine.InstalledRecognizers()[0].Culture.ToString() + " as the default culture.",

    SpeechRecognitionEngine.InstalledRecognizers()[0].Culture.ToString()

    이부분

    SpeechRecognitionEngine 객체의 인스턴스가 Null 인 경우의 IF 문으로 들어왔는데, [0] 인덱스로 값을 얻으려고 하고있네요.

    이부분을 고치시면 될것 같습니다.

    정해진 에러문구가 있다면, 해당 문구를 Const 선언하셔서 해당 메세지를 저 부분에 셋팅하는 방식으로 해결보시면 될것 같네요.

    즐프하세요~


    프로그램 개발에는 정답이 없다.

    • 답변으로 표시됨 SMPark82 2015년 8월 13일 목요일 오전 1:07
    2015년 7월 31일 금요일 오전 12:57

모든 응답

  • IndexOutOfRangeException이 발생한 것입니다.

    https://msdn.microsoft.com/en-us/library/system.indexoutofrangeexception
    IndexOutOfRangeException Class

    http://stackoverflow.com/questions/24812679/what-is-an-index-out-of-range-exception-and-how-do-i-fix-it
    What is an “index out of range” exception, and how do I fix it? [duplicate]

    for문이나 foreach 문에서 발생합니다. 보여주신 코드에 foreach문이 2개 보이는데 루프문 안에서 array element를 디버깅 창에서 확인해 보십시요.

    2015년 7월 27일 월요일 오전 12:34
  • 안녕하세요.

    가만보니까 여기서 나는것 같네요.

    참고하세요.

                    Console.WriteLine("The desired culture is not installed on this machine, the speech-engine will continue using "
                        + SpeechRecognitionEngine.InstalledRecognizers()[0].Culture.ToString() + " as the default culture.",

    SpeechRecognitionEngine.InstalledRecognizers()[0].Culture.ToString()

    이부분

    SpeechRecognitionEngine 객체의 인스턴스가 Null 인 경우의 IF 문으로 들어왔는데, [0] 인덱스로 값을 얻으려고 하고있네요.

    이부분을 고치시면 될것 같습니다.

    정해진 에러문구가 있다면, 해당 문구를 Const 선언하셔서 해당 메세지를 저 부분에 셋팅하는 방식으로 해결보시면 될것 같네요.

    즐프하세요~


    프로그램 개발에는 정답이 없다.

    • 답변으로 표시됨 SMPark82 2015년 8월 13일 목요일 오전 1:07
    2015년 7월 31일 금요일 오전 12:57