【问题标题】:SpeechSynthesis, Web Speech API, remove the delay after speaking has finished and the onend property firing?SpeechSynthesis,Web Speech API,消除说话完成后的延迟和 onend 属性触发?
【发布时间】:2022-09-27 22:54:18
【问题描述】:

我在 SpeechSynthesisUtterance 说话时显示动画图形。我正在使用 onend 属性来检测说话何时完成以删除动画图形。然而,在说话结束和 onend 事件触发之间存在显着延迟,这意味着即使说话已经结束,动画图形也会继续播放大约 1 秒。是否可以消除这种延迟?下面的代码是问题的简单演示。

let utterance = new SpeechSynthesisUtterance(\"Approximately a second delay after utterance has finished and the onend event firing\");
speechSynthesis.speak(utterance);
utterance.onend = function () {
console.log(\"There is a delay before this message appears?\");

}

  • 您可以使用boundary 事件并检查事件上的charIndex。如果它位于话语中倒数第二个单词的位置,请更新您的图形,而不是 onend
  • @morganney - 非常感谢您的评论。我已经尝试过您的解决方案,并且效果很好:)
  • 太好了,我添加了一个演示示例方法的答案。如果它适合您,请接受它作为答案。

标签: javascript api speech speech-synthesis


【解决方案1】:

此处不使用end 事件,而是使用boundary 事件根据正在说出的话语的evt.charIndex 从DOM 中删除某些内容的示例。

这会在倒数第二个单词说完后删除图形:

function getPenultimateWordEndingIndex(text) {
  const words = text.split(' ').filter(Boolean)

  // Can use words.slice(-1, -1)[0] for better browser support
  return text.lastIndexOf(words.at(-1))
}

const text = 'This image should be removed after hearing the word "event" spoken.'
const index = getPenultimateWordEndingIndex(text)
const graphic = document.getElementById('graphic')
const utter = new SpeechSynthesisUtterance(text)

utter.addEventListener('boundary', evt => {
  if (evt.charIndex >= index) {
    graphic.remove()
  }
})

document.getElementById('speak').addEventListener('click', () => {
  window.speechSynthesis.speak(utter)
})
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" width="100" id="graphic" />
<p>This image should be removed after hearing the word "event" spoken.</p>
<button id="speak">speak</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 2022-09-17
    • 1970-01-01
    • 2015-06-11
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多