1// Copyright 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/** 6 * @fileoverview The manager of speech recognition. 7 */ 8 9cr.define('speech', function() { 10 'use strict'; 11 12 /** 13 * @constructor 14 */ 15 function SpeechRecognitionManager(delegate) { 16 this.isActive = true; 17 this.delegate_ = delegate; 18 19 this.recognizer_ = new window.webkitSpeechRecognition(); 20 this.recognizer_.continuous = true; 21 this.recognizer_.interimResults = true; 22 this.recognizer_.lang = navigator.language; 23 24 this.recognizer_.onresult = this.onRecognizerResult_.bind(this); 25 if (this.delegate_) { 26 this.recognizer_.onstart = 27 this.delegate_.onSpeechRecognitionStarted.bind(this.delegate_); 28 this.recognizer_.onend = 29 this.delegate_.onSpeechRecognitionEnded.bind(this.delegate_); 30 this.recognizer_.onspeechstart = 31 this.delegate_.onSpeechStarted.bind(this.delegate_); 32 this.recognizer_.onspeechend = 33 this.delegate_.onSpeechEnded.bind(this.delegate_); 34 this.recognizer_.onerror = this.onRecognizerError_.bind(this); 35 } 36 } 37 38 /** 39 * Called when new speech recognition results arrive. 40 * 41 * @param {Event} speechEvent The event to contain the recognition results. 42 * @private 43 */ 44 SpeechRecognitionManager.prototype.onRecognizerResult_ = function( 45 speechEvent) { 46 // Do not collect interim result for now. 47 var result = ''; 48 var isFinal = false; 49 for (var i = 0; i < speechEvent.results.length; i++) { 50 if (speechEvent.results[i].isFinal) 51 isFinal = true; 52 result += speechEvent.results[i][0].transcript; 53 } 54 if (this.delegate_) 55 this.delegate_.onSpeechRecognized(result, isFinal); 56 }; 57 58 /** 59 * Called when an error happens in speech recognition. 60 * 61 * @param {SpeechRecognitionError} error The error data. 62 * @private 63 */ 64 SpeechRecognitionManager.prototype.onRecognizerError_ = function(error) { 65 if (error.error == 'language-not-supported') { 66 // Falls back to English and restart. 67 this.recognizer_.lang = 'en-US'; 68 this.start(); 69 } else { 70 this.delegate_.onSpeechRecognitionError(error); 71 } 72 }; 73 74 /** 75 * Starts the speech recognition through webkitSpeechRecognition. 76 */ 77 SpeechRecognitionManager.prototype.start = function() { 78 this.recognizer_.start(); 79 }; 80 81 /** 82 * Stops the ongoing speech recognition. 83 */ 84 SpeechRecognitionManager.prototype.stop = function() { 85 this.recognizer_.abort(); 86 }; 87 88 return { 89 SpeechRecognitionManager: SpeechRecognitionManager 90 }; 91}); 92