|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +class Notifier { |
| 4 | + constructor() { |
| 5 | + this.handlers = []; |
| 6 | + } |
| 7 | + |
| 8 | + addHandler(handler) { |
| 9 | + this.handlers.push(handler); |
| 10 | + } |
| 11 | + |
| 12 | + notify() { |
| 13 | + this.handlers.forEach(handler => handler()); |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +class Recognition { |
| 18 | + constructor(notifier) { |
| 19 | + this.notifier = notifier; |
| 20 | + this._text = ''; |
| 21 | + } |
| 22 | + |
| 23 | + get text() { |
| 24 | + return this._text; |
| 25 | + } |
| 26 | + |
| 27 | + set text(transcript) { |
| 28 | + this._text = transcript; |
| 29 | + this.notifyUpdate(); |
| 30 | + } |
| 31 | + |
| 32 | + addHandler(handler) { |
| 33 | + this.notifier.addHandler(handler); |
| 34 | + } |
| 35 | + |
| 36 | + notifyUpdate() { |
| 37 | + this.notifier.notify(); |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +class ViewModel { |
| 42 | + constructor(words) { |
| 43 | + this.words = words; |
| 44 | + this.currentParagraph = document.createElement('p'); |
| 45 | + this.words.appendChild(this.currentParagraph); |
| 46 | + this.recognition = new Recognition(new Notifier()); |
| 47 | + |
| 48 | + this.recognition.addHandler(() => { |
| 49 | + this.text = this.recognition.text; |
| 50 | + }); |
| 51 | + this.recognition.notifyUpdate(); |
| 52 | + } |
| 53 | + |
| 54 | + recognize(ev) { |
| 55 | + const transcript = Array.from(ev.results) |
| 56 | + .map(result => result[0].transcript) |
| 57 | + .join(''); |
| 58 | + |
| 59 | + this.recognition.text = transcript; |
| 60 | + this.currentParagraph.textContent = this.text; |
| 61 | + |
| 62 | + if (!ev.results[0].isFinal) { return; } |
| 63 | + |
| 64 | + this.currentParagraph = document.createElement('p'); |
| 65 | + this.words.appendChild(this.currentParagraph); |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; |
| 70 | + |
| 71 | +const recognition = new SpeechRecognition(); |
| 72 | +recognition.interimResults = true; |
| 73 | +const words = document.querySelector('.words'); |
| 74 | +const vm = new ViewModel(words); |
| 75 | + |
| 76 | +recognition.addEventListener('result', ev => vm.recognize(ev)); |
| 77 | +recognition.addEventListener('end', recognition.start); |
| 78 | +recognition.start(); |
0 commit comments