[我在这里使用JS文本与SpeechSynthesis进行语音通信,并且在有限的单词/句子数量下可以正常工作,但是我添加所有博客段落的时间超过了2-3k时,它无法正常工作,直到部分转换为止并自动停止。因此,我该如何添加不限字数或转换成语音的总页面内容。
[注意:我也尝试了js号(),但效果很好,但是我想要一个暂停/停止选项,所以我用了这个。因此,如果还有其他工作方式,请提出建议。
const msg = new SpeechSynthesisUtterance();
let voices = [];
const voicesDropdown = document.querySelector('[name="voice"]');
const options = document.querySelectorAll('[type="range"],[name="text"]');
const speakButton = document.querySelector('#speak');
const stopButton = document.querySelector('#stop');
msg.text = document.querySelector('[name="text"]').value;
function populateVoices() {
voices = this.getVoices();
voicesDropdown.innerHTML = voices.map(voice => `<option value="${voice.name}">${voice.name}(${voice.lang})</option>`).join('');
}
function setVoice() {
msg.voice = voices.find(voice => voice.name === this.value);
toggle();
}
function toggle(startOver = true) { //true is for it will not stop if language changes
speechSynthesis.cancel();
if (startOver) {
speechSynthesis.speak(msg);
}
}
function setOption() {
// console.log(this.name, this.value);
msg[this.name] = this.value;
toggle();
}
speechSynthesis.addEventListener('voiceschanged', populateVoices);
voicesDropdown.addEventListener('change', setVoice);
options.forEach(option => option.addEventListener('change', setOption));
speakButton.addEventListener('click', toggle);
<div class="voiceinator">
<select name="voice" id="voices">
<option value="">Select a voice</option>
</select>
<label for="rate">Rate:</label>
<input type="range" name="rate" min="0" max="3" value="1" step="0.1">
<label for="pitch">Pitch:</label>
<input type="range" name="pitch" min="0" max="2" value="1" step="0.1">
<textarea name="text"></textarea>
<button id="stop">Stop!</button>
<button id="speak">Speak</button>
</div>
这是known bug。 workaround每14秒发布一份简历。