apps/voice-recognition/public/speech.js
function(commands, resetCommands) {

      // resetCommands defaults to true
      if (resetCommands === undefined) {
        resetCommands = true;
      } else {
        resetCommands = !!resetCommands;
      }

      // Abort previous instances of recognition already running
      if (recognition && recognition.abort) {
        recognition.abort();
      }

      // initiate SpeechRecognition
      recognition = new SpeechRecognition();

      // Set the max number of alternative transcripts to try and match with a command
      recognition.maxAlternatives = 5;

      // In HTTPS, turn off continuous mode for faster results.
      // In HTTP,  turn on  continuous mode for much slower results, but no repeating security notices
      recognition.continuous = root.location.protocol === 'http:';

      // Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage()
      recognition.lang = 'en-US';

      recognition.onstart   = function()      { invokeCallbacks(callbacks.start); };

      recognition.onerror   = function(event) {
        invokeCallbacks(callbacks.error);
        switch (event.error) {
        case 'network':
          invokeCallbacks(callbacks.errorNetwork);
          break;
        case 'not-allowed':
        case 'service-not-allowed':
          // if permission to use the mic is denied, turn off auto-restart
          autoRestart = false;
          // determine if permission was denied by user or automatically.
          if (new Date().getTime()-lastStartedAt < 200) {
            invokeCallbacks(callbacks.errorPermissionBlocked);
          } else {
            invokeCallbacks(callbacks.errorPermissionDenied);
          }
          break;
        }
      };

      recognition.onend     = function() {
        invokeCallbacks(callbacks.end);
        // annyang will auto restart if it is closed automatically and not by user action.
        if (autoRestart) {
          // play nicely with the browser, and never restart annyang automatically more than once per second
          var timeSinceLastStart = new Date().getTime()-lastStartedAt;
          if (timeSinceLastStart < 1000) {
            setTimeout(root.annyang.start, 1000-timeSinceLastStart);
          } else {
            root.annyang.start();
          }
        }
      };

      recognition.onresult  = function(event) {
        invokeCallbacks(callbacks.result);
        var results = event.results[event.resultIndex];
        var commandText;
        // go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above)
        for (var i = 0; i<results.length; i++) {
          // the text recognized
          commandText = results[i].transcript.trim();

          // do stuff
          $('#speechActivity').html('<h2>Last voice command: ' + commandText + '</h2>');

          if (debugState) {
//            document.getElementById('speechActivity').innerHTML = commandText;
            root.console.log('Speech recognized: %c'+commandText, debugStyle);
          }

          // try and match recognized text to one of the commands on the list
          for (var j = 0, l = commandsList.length; j < l; j++) {
            var result = commandsList[j].command.exec(commandText);
            if (result) {
              var parameters = result.slice(1);
              if (debugState) {
                root.console.log('command matched: %c'+commandsList[j].originalPhrase, debugStyle);
                if (parameters.length) {
                  root.console.log('with parameters', parameters);
                }
              }
              // execute the matched command
              commandsList[j].callback.apply(this, parameters);
              invokeCallbacks(callbacks.resultMatch);
              return true;
            }
          }
        }
        invokeCallbacks(callbacks.resultNoMatch);
        return false;
      };

      // build commands list
      if (resetCommands) {
        commandsList = [];
      }
      if (commands.length) {
        this.addCommands(commands);
      }
    }
function(commands, resetCommands) {

      // resetCommands defaults to true
      if (resetCommands === undefined) {
        resetCommands = true;
      } else {
        resetCommands = !!resetCommands;
      }

      // Abort previous instances of recognition already running
      if (recognition && recognition.abort) {
        recognition.abort();
      }

      // initiate SpeechRecognition
      recognition = new SpeechRecognition();

      // Set the max number of alternative transcripts to try and match with a command
      recognition.maxAlternatives = 5;

      // In HTTPS, turn off continuous mode for faster results.
      // In HTTP,  turn on  continuous mode for much slower results, but no repeating security notices
      recognition.continuous = root.location.protocol === 'http:';

      // Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage()
      recognition.lang = 'en-US';

      recognition.onstart   = function()      { invokeCallbacks(callbacks.start); };

      recognition.onerror   = function(event) {
        invokeCallbacks(callbacks.error);
        switch (event.error) {
        case 'network':
          invokeCallbacks(callbacks.errorNetwork);
          break;
        case 'not-allowed':
        case 'service-not-allowed':
          // if permission to use the mic is denied, turn off auto-restart
          autoRestart = false;
          // determine if permission was denied by user or automatically.
          if (new Date().getTime()-lastStartedAt < 200) {
            invokeCallbacks(callbacks.errorPermissionBlocked);
          } else {
            invokeCallbacks(callbacks.errorPermissionDenied);
          }
          break;
        }
      };

      recognition.onend     = function() {
        invokeCallbacks(callbacks.end);
        // annyang will auto restart if it is closed automatically and not by user action.
        if (autoRestart) {
          // play nicely with the browser, and never restart annyang automatically more than once per second
          var timeSinceLastStart = new Date().getTime()-lastStartedAt;
          if (timeSinceLastStart < 1000) {
            setTimeout(root.annyang.start, 1000-timeSinceLastStart);
          } else {
            root.annyang.start();
          }
        }
      };

      recognition.onresult  = function(event) {
        invokeCallbacks(callbacks.result);
        var results = event.results[event.resultIndex];
        var commandText;
        // go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above)
        for (var i = 0; i<results.length; i++) {
          // the text recognized
          commandText = results[i].transcript.trim();

          // do stuff
          $('#speechActivity').html('<h2>Last voice command: ' + commandText + '</h2>');

          if (debugState) {
//            document.getElementById('speechActivity').innerHTML = commandText;
            root.console.log('Speech recognized: %c'+commandText, debugStyle);
          }

          // try and match recognized text to one of the commands on the list
          for (var j = 0, l = commandsList.length; j < l; j++) {
            var result = commandsList[j].command.exec(commandText);
            if (result) {
              var parameters = result.slice(1);
              if (debugState) {
                root.console.log('command matched: %c'+commandsList[j].originalPhrase, debugStyle);
                if (parameters.length) {
                  root.console.log('with parameters', parameters);
                }
              }
              // execute the matched command
              commandsList[j].callback.apply(this, parameters);
              invokeCallbacks(callbacks.resultMatch);
              return true;
            }
          }
        }
        invokeCallbacks(callbacks.resultNoMatch);
        return false;
      };

      // build commands list
      if (resetCommands) {
        commandsList = [];
      }
      if (commands.length) {
        this.addCommands(commands);
      }
    }
function ( commands , resetCommands ) { // resetCommands defaults to true if ( resetCommands === undefined ) { resetCommands = true ; } else { resetCommands = ! ! resetCommands ; } // Abort previous instances of recognition already running if ( recognition && recognition . abort ) { recognition . abort ( ) ; } // initiate SpeechRecognition recognition = new SpeechRecognition ( ) ; // Set the max number of alternative transcripts to try and match with a command recognition . maxAlternatives = 5 ; // In HTTPS, turn off continuous mode for faster results. // In HTTP,  turn on  continuous mode for much slower results, but no repeating security notices recognition . continuous = root . location . protocol === 'http:' ; // Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage() recognition . lang = 'en-US' ; recognition . onstart = function ( ) { invokeCallbacks ( callbacks . start ) ; } ; recognition . onerror = function ( event ) { invokeCallbacks ( callbacks . error ) ; switch ( event . error ) { case 'network' : invokeCallbacks ( callbacks . errorNetwork ) ; break ; case 'not-allowed' : case 'service-not-allowed' : // if permission to use the mic is denied, turn off auto-restart autoRestart = false ; // determine if permission was denied by user or automatically. if ( new Date ( ) . getTime ( ) - lastStartedAt < 200 ) { invokeCallbacks ( callbacks . errorPermissionBlocked ) ; } else { invokeCallbacks ( callbacks . errorPermissionDenied ) ; } break ; } } ; recognition . onend = function ( ) { invokeCallbacks ( callbacks . end ) ; // annyang will auto restart if it is closed automatically and not by user action. if ( autoRestart ) { // play nicely with the browser, and never restart annyang automatically more than once per second var timeSinceLastStart = new Date ( ) . getTime ( ) - lastStartedAt ; if ( timeSinceLastStart < 1000 ) { setTimeout ( root . annyang . start , 1000 - timeSinceLastStart ) ; } else { root . annyang . start ( ) ; } } } ; recognition . onresult = function ( event ) { invokeCallbacks ( callbacks . result ) ; var results = event . results [ event . resultIndex ] ; var commandText ; // go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above) for ( var i = 0 ; i < results . length ; i ++ ) { // the text recognized commandText = results [ i ] . transcript . trim ( ) ; // do stuff $ ( '#speechActivity' ) . html ( '<h2>Last voice command: ' + commandText + '</h2>' ) ; if ( debugState ) { //            document.getElementById('speechActivity').innerHTML = commandText; root . console . log ( 'Speech recognized: %c' + commandText , debugStyle ) ; } // try and match recognized text to one of the commands on the list for ( var j = 0 , l = commandsList . length ; j < l ; j ++ ) { var result = commandsList [ j ] . command . exec ( commandText ) ; if ( result ) { var parameters = result . slice ( 1 ) ; if ( debugState ) { root . console . log ( 'command matched: %c' + commandsList [ j ] . originalPhrase , debugStyle ) ; if ( parameters . length ) { root . console . log ( 'with parameters' , parameters ) ; } } // execute the matched command commandsList [ j ] . callback . apply ( this , parameters ) ; invokeCallbacks ( callbacks . resultMatch ) ; return true ; } } } invokeCallbacks ( callbacks . resultNoMatch ) ; return false ; } ; // build commands list if ( resetCommands ) { commandsList = [ ] ; } if ( commands . length ) { this . addCommands ( commands ) ; } }
Initialize annyang with a list of commands to recognize.

### Examples:

var commands = {'hello :name': helloFunction};
var commands2 = {'hi': helloFunction};

// initialize annyang, overwriting any previously added commands
annyang.init(commands, true);
// adds an additional command without removing the previous commands
annyang.init(commands2, false);

As of v1.1.0 it is no longer required to call init(). Just start() listening whenever you want, and addCommands() whenever, and as often as you like.

@param {Object} commands - Commands that annyang should listen to
@param {Boolean} [resetCommands=true] - Remove all commands before initializing?
@method init
@deprecated
@see [Commands Object](#commands-object)
Initialize annyang with a list of commands to recognize .