SpeechSynthesisUtterance: rate 属性
SpeechSynthesisUtterance 接口的 rate 属性用于获取和设置语音播报的速度。
如果未设置,将使用默认值 1。
值
一个表示语速值的浮点数。它的范围可以从 0.1(最低)到 10(最高),其中 1 是当前平台或语音的默认语速,应对应正常说话速度。其他值则相对于此作为百分比,例如 2 表示两倍速,0.5 表示半速,以此类推。
某些语音合成引擎或语音可能会进一步限制最小和最大语速。如果使用了 SSML,此值将被标记中的 prosody 标签覆盖。
示例
调整播放速度
在此示例中,我们可以使用滑块调整播放速度,然后点击“播放”按钮来播放语音。
HTML
html
<p id="text">It was a dark and stormy night.</p>
<div id="rate-control">
<label for="rate">Rate:</label>
<input type="range" min="0.5" max="2" value="1" step="0.1" id="rate" />
</div>
<button id="play">Play</button>
CSS
css
body {
font-family: sans-serif;
}
#rate-control {
display: flex;
align-items: center;
gap: 1rem;
margin: 1rem 0;
}
JavaScript
js
const synth = window.speechSynthesis;
const text = document.querySelector("#text");
const play = document.querySelector("#play");
const rate = document.querySelector("#rate");
function speak() {
if (synth.speaking) {
synth.cancel();
}
const utterThis = new SpeechSynthesisUtterance(text.textContent);
utterThis.addEventListener("error", () => {
console.error("SpeechSynthesisUtterance error");
});
utterThis.rate = rate.value;
synth.speak(utterThis);
}
play.addEventListener("click", speak);
输出
规范
| 规范 |
|---|
| Web Speech API # dom-speechsynthesisutterance-rate |
浏览器兼容性
加载中…