OLD | NEW |
(Empty) | |
| 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 |
| 5 function 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 |
| 16 VoiceInput.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 mic 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 for (var i = 0; i < this.finalResult_.length; i++) { |
| 50 var keyEvent = { |
| 51 keyIdentifier: this.finalResult_.charAt(i) |
| 52 }; |
| 53 sendKeyEvent(keyEvent); |
| 54 } |
| 55 }, |
| 56 |
| 57 /** |
| 58 * Speech recognizer returns an error. |
| 59 * @param{Event} e The SpeechRecognitionError event that is raised each time |
| 60 * there is an error. |
| 61 */ |
| 62 onErrorHandler: function(e) { |
| 63 console.error('error code = ' + e.error); |
| 64 }, |
| 65 |
| 66 /** |
| 67 * Speech recognition ended. Reset mic key's icon. |
| 68 */ |
| 69 onEndHandler: function() { |
| 70 if (this.keyboard_.classList.contains('audio')) |
| 71 this.keyboard_.classList.remove('audio'); |
| 72 this.recognizing_ = false; |
| 73 } |
| 74 }; |
OLD | NEW |