javascript - 跟踪 SpeechSynthesis API 所说的单词
问题描述
我正在编写一个软件程序,它使用 Web SpeechSynthesis API 读取文本并显示正在说出的单词。
语音 API 确实有一个onboundary
用于执行此操作的事件,但它不适用于大多数语音。因此,唯一的选择是通过计算说出每个字符所需的时间来大致跟踪它,然后像这样使用它来跟踪单词:
function speak(text) {
return new Promise(resolve => {
let msg = new SpeechSynthesisUtterance();
let start = 0;
msg.text = text;
msg.onstart = (e) => {
var evt = new CustomEvent('tts-play');
window.dispatchEvent(evt);
start = performance.now();
};
msg.onend = (e) => resolve(performance.now() - start);
speechSynthesis.speak(msg);
});
}
function go() {
let calibrate = 'Calibrating speech engine';
let actualText = 'This is the text for which I want to track which word is spoken. As you can see, the text loses sync – Can you help me fix it?';
speak(calibrate).then(ms => {
let msPerChar = ms / calibrate.length;
console.log("ms per char is ", msPerChar);
let words = actualText.split(/\s+/);
let track = () => {
let delay = 0;
for (let word of words) {
setTimeout(() => $('#theWord').text(word), delay);
delay += msPerChar * word.length;
}
};
window.addEventListener('tts-play', track());
speak(actualText);
});
}
body, button {
font-size: 1.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>Speech synthesis demo</p>
<button onclick="go()">Start</button>
<p>Spoken word: <span id="theWord"></span></p>
</div>
正如你所看到的,文本失去了同步,通过计算来跟踪单词的方法msPerChar
需要一些微调。
有什么想法可以改进吗?
谢谢。
PS这是一个jsfiddle,因为它更容易修改:https ://jsfiddle.net/superasn/7oyd0p4f/25/
解决方案
推荐阅读
- android - 离子构建 android 错误无法 GET 'http://jcenter.bintray.com ...'
- android - 我如何跳过 okhttp 缓存并获取响应并缓存新响应
- css - 引导选项卡超出屏幕宽度
- asynchronous - 如何重构 IEnumerable
执行数据读取器 到异步方法 - shell - 如何根据文件中的行号提取特定行
- ios - 按钮未呈现
- java - 尝试运行 Tomcat 时出现异常
- selenium - Angular 应用程序的自动化工具?
- java - 我怎样才能让我的“敌人”追逐“目标”-Java
- ios - 从 iOS“安全区域”中排除导航栏