|
| 1 | +/* |
| 2 | + * If not stated otherwise in this file or this component's LICENSE file the |
| 3 | + * following copyright and licenses apply: |
| 4 | + * |
| 5 | + * Copyright 2020 Metrological |
| 6 | + * |
| 7 | + * Licensed under the Apache License, Version 2.0 (the License); |
| 8 | + * you may not use this file except in compliance with the License. |
| 9 | + * You may obtain a copy of the License at |
| 10 | + * |
| 11 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | + * |
| 13 | + * Unless required by applicable law or agreed to in writing, software |
| 14 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | + * See the License for the specific language governing permissions and |
| 17 | + * limitations under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +/* global SpeechSynthesisErrorEvent */ |
| 21 | +function flattenStrings(series = []) { |
| 22 | + const flattenedSeries = [] |
| 23 | + |
| 24 | + for (var i = 0; i < series.length; i++) { |
| 25 | + if (typeof series[i] === 'string' && !series[i].includes('PAUSE-')) { |
| 26 | + flattenedSeries.push(series[i]) |
| 27 | + } else { |
| 28 | + break |
| 29 | + } |
| 30 | + } |
| 31 | + // add a "word boundary" to ensure the Announcer doesn't automatically try to |
| 32 | + // interpret strings that look like dates but are not actually dates |
| 33 | + // for example, if "Rising Sun" and "1993" are meant to be two separate lines, |
| 34 | + // when read together, "Sun 1993" is interpretted as "Sunday 1993" |
| 35 | + return [flattenedSeries.join(',\b ')].concat(series.slice(i)) |
| 36 | +} |
| 37 | + |
| 38 | +function delay(pause) { |
| 39 | + return new Promise(resolve => { |
| 40 | + setTimeout(resolve, pause) |
| 41 | + }) |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * Speak a string |
| 46 | + * |
| 47 | + * @param {string} phrase Phrase to speak |
| 48 | + * @param {SpeechSynthesisUtterance[]} utterances An array which the new SpeechSynthesisUtterance instance representing this utterance will be appended |
| 49 | + * @return {Promise<void>} Promise resolved when the utterance has finished speaking, and rejected if there's an error |
| 50 | + */ |
| 51 | +function speak(phrase, utterances, lang = 'en-US') { |
| 52 | + const synth = window.speechSynthesis |
| 53 | + return new Promise((resolve, reject) => { |
| 54 | + const utterance = new SpeechSynthesisUtterance(phrase) |
| 55 | + utterance.lang = lang |
| 56 | + utterance.onend = () => { |
| 57 | + resolve() |
| 58 | + } |
| 59 | + utterance.onerror = e => { |
| 60 | + reject(e) |
| 61 | + } |
| 62 | + utterances.push(utterance) |
| 63 | + synth.speak(utterance) |
| 64 | + }) |
| 65 | +} |
| 66 | + |
| 67 | +function speakSeries(series, lang, root = true) { |
| 68 | + const synth = window.speechSynthesis |
| 69 | + const remainingPhrases = flattenStrings(Array.isArray(series) ? series : [series]) |
| 70 | + const nestedSeriesResults = [] |
| 71 | + /* |
| 72 | + We hold this array of SpeechSynthesisUtterances in order to prevent them from being |
| 73 | + garbage collected prematurely on STB hardware which can cause the 'onend' events of |
| 74 | + utterances to not fire consistently. |
| 75 | + */ |
| 76 | + const utterances = [] |
| 77 | + let active = true |
| 78 | + |
| 79 | + const seriesChain = (async () => { |
| 80 | + try { |
| 81 | + while (active && remainingPhrases.length) { |
| 82 | + const phrase = await Promise.resolve(remainingPhrases.shift()) |
| 83 | + if (!active) { |
| 84 | + // Exit |
| 85 | + // Need to check this after the await in case it was cancelled in between |
| 86 | + break |
| 87 | + } else if (typeof phrase === 'string' && phrase.includes('PAUSE-')) { |
| 88 | + // Pause it |
| 89 | + let pause = phrase.split('PAUSE-')[1] * 1000 |
| 90 | + if (isNaN(pause)) { |
| 91 | + pause = 0 |
| 92 | + } |
| 93 | + await delay(pause) |
| 94 | + } else if (typeof phrase === 'string' && phrase.length) { |
| 95 | + // Speak it |
| 96 | + const totalRetries = 3 |
| 97 | + let retriesLeft = totalRetries |
| 98 | + while (active && retriesLeft > 0) { |
| 99 | + try { |
| 100 | + await speak(phrase, utterances, lang) |
| 101 | + retriesLeft = 0 |
| 102 | + } catch (e) { |
| 103 | + // eslint-disable-next-line no-undef |
| 104 | + if (e instanceof SpeechSynthesisErrorEvent) { |
| 105 | + if (e.error === 'network') { |
| 106 | + retriesLeft-- |
| 107 | + console.warn(`Speech synthesis network error. Retries left: ${retriesLeft}`) |
| 108 | + await delay(500 * (totalRetries - retriesLeft)) |
| 109 | + } else if (e.error === 'canceled' || e.error === 'interrupted') { |
| 110 | + // Cancel or interrupt error (ignore) |
| 111 | + retriesLeft = 0 |
| 112 | + } else { |
| 113 | + throw new Error(`SpeechSynthesisErrorEvent: ${e.error}`) |
| 114 | + } |
| 115 | + } else { |
| 116 | + throw e |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + } else if (typeof phrase === 'function') { |
| 121 | + const seriesResult = speakSeries(phrase(), lang, false) |
| 122 | + nestedSeriesResults.push(seriesResult) |
| 123 | + await seriesResult.series |
| 124 | + } else if (Array.isArray(phrase)) { |
| 125 | + // Speak it (recursively) |
| 126 | + const seriesResult = speakSeries(phrase, lang, false) |
| 127 | + nestedSeriesResults.push(seriesResult) |
| 128 | + await seriesResult.series |
| 129 | + } |
| 130 | + } |
| 131 | + } finally { |
| 132 | + active = false |
| 133 | + } |
| 134 | + })() |
| 135 | + return { |
| 136 | + series: seriesChain, |
| 137 | + get active() { |
| 138 | + return active |
| 139 | + }, |
| 140 | + append: toSpeak => { |
| 141 | + remainingPhrases.push(toSpeak) |
| 142 | + }, |
| 143 | + cancel: () => { |
| 144 | + if (!active) { |
| 145 | + return |
| 146 | + } |
| 147 | + if (root) { |
| 148 | + synth.cancel() |
| 149 | + } |
| 150 | + nestedSeriesResults.forEach(nestedSeriesResults => { |
| 151 | + nestedSeriesResults.cancel() |
| 152 | + }) |
| 153 | + active = false |
| 154 | + }, |
| 155 | + } |
| 156 | +} |
| 157 | + |
| 158 | +let currentSeries |
| 159 | +export default function(toSpeak, lang) { |
| 160 | + currentSeries && currentSeries.cancel() |
| 161 | + currentSeries = speakSeries(toSpeak, lang) |
| 162 | + return currentSeries |
| 163 | +} |
0 commit comments