首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SpeechSynthesis,Web,删除发言结束后的延迟和onend属性的触发?

SpeechSynthesis,Web,删除发言结束后的延迟和onend属性的触发?
EN

Stack Overflow用户
提问于 2021-12-17 13:36:54
回答 1查看 163关注 0票数 0

当SpeechSynthesisUtterance发言时,我正在显示一个动画图形。我正在使用onend属性来检测说话结束时删除动画图形。然而,在演讲结束和现场事件触发之间有一个明显的延迟,这意味着动画图形继续播放大约1秒,即使演讲已经结束。有可能消除这一延误吗?下面的代码是这个问题的简单演示。

代码语言:javascript
复制
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?");

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-27 14:54:18

这里有一个示例,说明如何使用end事件从DOM中删除某些内容,而不是使用boundary事件,该示例基于正在说话的evt.charIndex

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

代码语言:javascript
复制
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)
})
代码语言:javascript
复制
<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. (accept chrome/android which doesn't fire boundary events)</p>
<button id="speak">speak</button>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70394044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档