使用SSML时Chrome及Edge浏览器中SpeechSynthesisUtterance的onmark事件无法触发
问题根因
- Chromium 内核(Chrome、Edge 均基于该内核)的 Web Speech API 不会解析
SpeechSynthesisUtterance.text字段中的 SSML 标签,你写入的<mark>标签会被识别为普通文本内容,无法触发对应事件。 - 当前 Chromium 内核浏览器尚未实现
onmark事件的触发逻辑,即便通过支持的 SSML 解析方式注入标记,也无法触发该回调,该事件目前仅在少量移动端、非主流浏览器中可用。
替代实现方案
你可以通过onboundary事件配合预设文本偏移量的方式实现类似标记触发效果,示例代码如下:
// 预设标记点对应的文本索引和名称 const markMap = { 0: 'w1', // Hello的起始位置 6: 'w2', // my的起始位置 9: 'w3', // name的起始位置 14: 'w4', // is的起始位置 17: 'w5' // John的起始位置 } function Speak() { var utterance = new SpeechSynthesisUtterance(); utterance.onboundary = function (event) { document.getElementById('output').innerHTML += 'onboundary Event: ' + event.toString() + "<br/>"; // 判断当前边界是否为预设标记点 if (markMap[event.charIndex]) { document.getElementById('output').innerHTML += `模拟mark事件: ${markMap[event.charIndex]}<br/>`; } }; utterance.text = 'Hello my name is John.'; utterance.lang = 'en-US'; utterance.voice = voices[0]; synth.speak(utterance); };
内容的提问来源于stack exchange,提问作者kyletme
相关产品推荐
相关产品推荐

