speech

by ajai jothi

JavaScript

class Questions {
  constructor(questions) {
    this.questions = questions;
    this.currentIndex = 0;
    this.MAX = this.questions.length - 1;

    // answers hash
    this.answers = questions.reduce((hash, q) => {
      hash[q] = '';
      return hash;
    }, {});

    this.initSpeech();
  }

  initSpeech() {
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;

    this.speechSynthesis = window.speechSynthesis;

    this.recognition = new webkitSpeechRecognition();

    this.recognition.continuous = true;
    this.recognition.interimResults = false;

    this.recognition.onresult = this.recognize.bind(this);
  }

  recognize(event) {
    const last = event.results.length - 1;
    const result = event.results[last][0].transcript;

    if (result.includes('yes')) {
      this.setAnswer('Yes');
      this.next();
    } else if (result.includes('no')) {
      this.setAnswer('No');
      this.next();
    } else {
      // ask same question again
      this.say('Can\'t recognize your answer');
      this.ask();
    }
  }

  setAnswer(answer) {
    this.answers[this.questions[this.currentIndex]] = answer;
  }

  start() {
    this.recognition.start();

    this.ask();

    return this;
  }

  stop() {
    this.recognition.stop();

    this.onComplete && this.onComplete(this.answers);
  }

  ask() {
    const questionToAsk = this.questions[this.currentIndex];
    this.say(questionToAsk);
  }

  say(msg) {
    const synth = new SpeechSynthesisUtterance(msg);
    this.speechSynthesis.speak(synth);
  }

  next() {
    if (this.currentIndex < this.MAX) {
      this.currentIndex++;
      this.ask();
    } else {
      this.stop();
    }
  }

  getAnswers() {
    return this.answers;
  }

  static create(questions) {
    return new Questions(questions);
  }
}

// const q = new Questions(['Question 1?', 'Question 2?', 'Question 3?']);
const q = Questions.create(['Question 1?', 'Question 2?', 'Question 3?']);

q.start().onComplete =...