Skip to content

Instantly share code, notes, and snippets.

@Garciat
Created March 1, 2015 17:51
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Garciat/56ce79f9f533f59b79ff to your computer and use it in GitHub Desktop.
function beginSpeechRecognition(options) {
options = options || {};
var engine = new webkitSpeechRecognition();
Object.keys(options).forEach(function (key) {
engine[key] = options[key];
});
engine.start();
var failed = false;
var recognitions = Rx.Observable.create(function (observer) {
engine.addEventListener('result', function (recognition) {
observer.onNext(recognition);
});
engine.addEventListener('error', function (err) {
failed = true;
observer.onError(err);
});
engine.addEventListener('end', function () {
observer.onCompleted();
});
});
var lifecycle = Rx.Observable.create(function (observer) {
engine.addEventListener('start', function () {
var alive = true;
observer.onNext(alive);
});
engine.addEventListener('end', function () {
var alive = false;
observer.onNext(alive);
observer.onCompleted();
});
});
var phrases = recognitions.map(function (recognition) {
var transcripts = [];
for (var i = 0; i < recognition.results.length; ++i) {
var result = recognition.results[i];
var alternatives = extractAlternatives(result);
alternatives.forEach(function (alternative) {
transcripts.push(alternative.transcript);
});
}
return transcripts.join('');
});
var results = recognitions.flatMap(function (recognition) {
var results = [];
for (var i = recognition.resultIndex; i < recognition.results.length; ++i) {
var result = recognition.results[i];
results.push(result);
}
return results;
});
var finalResults = results.filter(function (result) {
return result.isFinal;
});
var alternatives = results.flatMap(extractAlternatives);
var finalAlternatives = finalResults.flatMap(extractAlternatives);
function extractAlternatives(result) {
var alternatives = [];
for (var i = 0; i < result.length; ++i) {
var alternative = result[i];
alternatives.push(alternative);
}
return alternatives;
}
function stop() {
engine.stop();
}
return {
stop: stop,
lifecycle: lifecycle,
recognitions: recognitions,
results: results,
finalResults: finalResults,
alternatives: alternatives,
finalAlternatives: finalAlternatives,
phrases: phrases
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment