Skip to content

Instantly share code, notes, and snippets.

@nfreear
Last active October 14, 2020 10:04
Show Gist options
  • Save nfreear/3b9de19a76df43b3f34b2380f5309f4b to your computer and use it in GitHub Desktop.
Save nfreear/3b9de19a76df43b3f34b2380f5309f4b to your computer and use it in GitHub Desktop.
A base class compatible with the Web API 'SpeechRecognition' spec.
/**
* A base class compatible with the Web API 'SpeechRecognition' spec.
*
* @author NDF, 13-Oct-2020.
* @see https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition
*/
const Event = window.Event;
const EventTarget = window.EventTarget;
export const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
export const SpeechRecognitionEvent = window.SpeechRecognitionEvent || window.webkitSpeechRecognitionEvent;
export const SpeechGrammarList = window.SpeechGrammarList || window.webkitSpeechGrammarList;
export const SPEECH_RECOGNITION_EVENTS =
'audioend,audiostart,end,error,nomatch,result,soundend,soundstart,speechend,speechstart,start'.split(',');
export /* abstract / interface */ class SpeechRecognitionBase extends EventTarget {
constructor () {
super(...arguments);
this.continuous = false;
this.grammars = new SpeechGrammarList(); // {length: 0}
this.interimResults = false;
this.lang = '';
this.maxAlternatives = 1;
this._eventHandlers();
// console.debug(this.constructor.name, this);
}
_notImplemented (label) {
console.warn(`SpeechRecognitionBase. Not implemented: '${label}()'`);
}
_eventHandlers () {
SPEECH_RECOGNITION_EVENTS.forEach(evName => {
const onEvent = `on${evName}`;
this[onEvent] = (ev) => this._notImplemented(onEvent);
});
}
// EventTarget.
addEventListener (evName) { this._notImplemented(`addEventListener (${evName})`); }
abort () { this._notImplemented('abort'); }
start () { this._notImplemented('start'); }
stop () { this._notImplemented('stop'); }
}
export class SpeechRecognitionEventBase extends Event {
constructor () {
super(...arguments);
this.emma = null; // Readonly; XML; Obsolete.
this.interpretation = null; // Readonly; Obsolete.
this.resultIndex = 0;
this.results = null; // { length: 0 }; // SpeechRecognitionResultList.
}
}
// export const speechRecognitionBase = new SpeechRecognitionBase();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment