在 JavaScript 中,我可以在通过 onload 或 onclick 调用的函数中将实验文本转换为语音。 在间隔定时器内时它不起作用。我想这与在中断定时器内设置中断有关。 关于如何每分钟一次语音消息的任何建议。
我使用的测试是 var 语音 = new SpeechSynthesisUtterance(“你好世界”); Window.speechSynthesis.speak(语音);
我接受此功能仅适用于某些浏览器和设备,并且是实验性的,但也被广泛使用。
我正在尝试为监控应用程序每分钟提供一份自动语音状态报告
实际上,您可以使用
setInterval
来做到这一点。请参阅下面的示例了解一种方法。
var messages = ['Hello', 'world', 'It\'s me', 'Good day','How are you?','Download complete'];
var frequency = 3000;
var myInterval = setInterval(speak,frequency);
function speak() {
let rand = Math.floor(Math.random() * (messages.length-1));
console.log(rand);
let speech = new SpeechSynthesisUtterance(messages[rand]);
window.speechSynthesis.speak(speech);
}
我只是从数组中随机选取单词,并每三秒说一次。您可以根据需要调整提供的代码以使其工作(每分钟说出您的状态)。
Intervals 与
speechSynthesis
API 完美配合。这是一个工作示例:
speech = new SpeechSynthesisUtterance("hello world");
// say "hello world" every 5 seconds
setInterval(() => window.speechSynthesis.speak(speech), 5000)
如果您想在“文本到语音”之前检查监控更新,您可以构建如下内容:
setInterval(() => {
// Perform some calucation about the current status ...
status = getStatusUpdateAsString();
// Prepare speech
speech = new SpeechSynthesisUtterance(status);
window.speechSynthesis.speak(speech);
}, 5000)
这里是一个使用
SpeechSynthesisUtterance
end 事件、AbortController
和 setTimeout
来自动执行计数器的示例。您应该能够根据您的具体需求进行调整:
let count = 1
let controller = new AbortController()
const synth = window.speechSynthesis
const utter = new SpeechSynthesisUtterance(count)
const text = document.getElementById('text')
const onUtterEnd = () => {
setTimeout(() => {
count = count + 1
utter.text = count
text.innerHTML = `<mark>${count}</mark>`
synth.speak(utter)
}, [500])
}
const start = () => {
text.innerHTML = `<mark>${count}</mark>`
controller = new AbortController()
utter.addEventListener('end', onUtterEnd, { signal: controller.signal })
synth.speak(utter)
}
const stop = () => {
controller.abort()
synth.cancel()
}
document.getElementById('start').addEventListener('click', start)
document.getElementById('stop').addEventListener('click', stop)
<button id="start">start</button>
<button id="stop">stop</button>
<p id="text"></p>
tts-react
以获取自定义控件或挂钩。