1// Copyright (c) 2013 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5function VoiceInput(keyboard) { 6 this.finaResult_ = null; 7 this.recognizing_ = false; 8 this.keyboard_ = keyboard; 9 this.recognition_ = new webkitSpeechRecognition(); 10 this.recognition_.onstart = this.onStartHandler.bind(this); 11 this.recognition_.onresult = this.onResultHandler.bind(this); 12 this.recognition_.onerror = this.onErrorHandler.bind(this); 13 this.recognition_.onend = this.onEndHandler.bind(this); 14}; 15 16VoiceInput.prototype = { 17 /** 18 * Event handler for mouse/touch down events. 19 */ 20 onDown: function() { 21 if (this.recognizing_) { 22 this.recognition_.stop(); 23 return; 24 } 25 this.recognition_.start(); 26 }, 27 28 /** 29 * Speech recognition started. Change microphone key's icon. 30 */ 31 onStartHandler: function() { 32 this.recognizing_ = true; 33 this.finalResult_ = ''; 34 if (!this.keyboard_.classList.contains('audio')) 35 this.keyboard_.classList.add('audio'); 36 }, 37 38 /** 39 * Speech recognizer returns a result. 40 * @param{Event} e The SpeechRecognition event that is raised each time 41 * there 42 * are any changes to interim or final results. 43 */ 44 onResultHandler: function(e) { 45 for (var i = e.resultIndex; i < e.results.length; i++) { 46 if (e.results[i].isFinal) 47 this.finalResult_ = e.results[i][0].transcript; 48 } 49 insertText(this.finalResult_); 50 }, 51 52 /** 53 * Speech recognizer returns an error. 54 * @param{Event} e The SpeechRecognitionError event that is raised each time 55 * there is an error. 56 */ 57 onErrorHandler: function(e) { 58 console.error('error code = ' + e.error); 59 }, 60 61 /** 62 * Speech recognition ended. Reset microphone key's icon. 63 */ 64 onEndHandler: function() { 65 if (this.keyboard_.classList.contains('audio')) 66 this.keyboard_.classList.remove('audio'); 67 this.recognizing_ = false; 68 } 69}; 70